public class User {
String name;
short age;
int height;
// Write your code here
public User(String name, short age, int height){
this.name=name;
this.age=age;
this.height=height;
}
public User(short age, int height, String name){
this.age=age;
this.height=height;
this.name=name;
}
public User(int height, short age, String name){
this.height=height;
this.age =age;
this.name=name;
}
public User(String name, int height, short age){
this.name=name;
this.height=height;
this.age=age;
}
public User(int height,String name,short age){
this.height=height;
this.name=name;
this.age=age;
}
public User(short age, String name, int height){
this.age=age;
this.name=name;
this.height=height;
}
public static void main(String[] args) {
User user1 = new User (35, 5, "Dinesh");
System.out.println(user1.name);
System.out.println(user1.height);
System.out.println(user1.age);
}
}
Compilation error
Under discussion
Comments (7)
- Popular
- New
- Old
You must be signed in to leave a comment
Switch/Cypher
1 November 2020, 15:19
Ah, this is overloading constructors right?
You can't just re-order the arguments, they need to be unique.
You only need one of those constructors, because they are all the same. Except in this case, it just won't compile.
You didn't link what task it was, if the task is just 'make a constructor' just one will do,
If it is 'overloading' then you need to find a way for each to be unique.
0
Dinesh
1 November 2020, 15:44
Task was to Create the appropriate number of constructors, so that the name, age, and height can be specified in any order
0
Switch/Cypher
1 November 2020, 15:53
Ok I tested it in my IDE - you need to cast one of your number parameters to a 'short' for it to compile.
0
Dinesh
1 November 2020, 18:56
Thanks It worked. But why explicit type casting needed in case of short?
A constructor is a template for objects of a class. How? I am not getting it.
0
Switch/Cypher
1 November 2020, 19:26
It's because the compiler has no idea which of the numbers you are supplying is the "short".
Consider:
How would the compiler know which constructor I called and where to store the supplied initialisations. Either of the numbers could be an int or a short.
So the casting sorts that:
Now it knows which of the two things that could be either int or short is which and calls the right constructor. Make sense?
+1
Switch/Cypher
1 November 2020, 19:36
Also, a constructor isn't really a TEMPLATE for objects of a class. The class is the template for the object.
A constructor is just a way of initialising some object variables when you create the object. You could use a default constructor and initialise the variables separately but it's a pain and makes for long-winded code, also, some variables might be accidentally set to null, which will cause problems:
Or you use a constructor to save space and for clarity, or to ENSURE that certain variables are initialised:
0
Dinesh
1 November 2020, 21:08
Thanks a lot to make me understand these stuff so well.
0