"Constructor have no explicit return type." What does it mean? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

"Constructor have no explicit return type." What does it mean?

As far as I knew that Constructor have no explicit return type. But according to the given example code, why they use return color; ? [The example given] public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } // Setter public void setColor(String c) { this.color = c; } // Getter public String getColor() { return color; } } public class Program { public static void main(String[] args) { //color will be "Red" Vehicle v1 = new Vehicle(); //color will be "Green" Vehicle v2 = new Vehicle("Green"); System.out.println(v2.getColor()); } } [PS. I am still a highschool and new to Java. Sorry]

9th Dec 2018, 8:55 AM
MsMiyuna
MsMiyuna - avatar
4 Answers
+ 2
getColor() is not a constructor. Vehicle and Vehicle(String) are. Constructors are called by runtime to create a new instance to the class, and new will retrieve the instance and link it with the variable you wish to store the instance in. That is why you must not specify any return type in the constructor. As for the methods (member functions like getters and setters), they can return any type of variable.
9th Dec 2018, 9:30 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 3
Miyuna☕ You can use methods to return variables for use in derived classes or other functions. Eg: public class Rectangle { int l; int b; int area() { return l*b; } public void print_area() { System.out.print(this.area()); } } Here I returned a value in a private method, and later called it in a public method. So its not necessary to use the value in main. If this is not what you meant, please let me know.
9th Dec 2018, 9:41 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
Ohh so you can only return any variable only in the main method?
9th Dec 2018, 9:34 AM
MsMiyuna
MsMiyuna - avatar
+ 1
👍👍👍👍 I get it now! Thank you very much for explaining it to me! 😊😅 There are just some of the codes that made me confused anyways, You're a life saver! 👍👍👍
9th Dec 2018, 9:50 AM
MsMiyuna
MsMiyuna - avatar