When calling a constructor from a constructor, we use the 'this' keyword. The 'this' keyword refers to the class name. Then how are the values set in the object when we are only referring to the class and not the object?
Student random = new student();
class Student {
int roll;
student() {
this student(13);
}
student(int roll) {
this.roll = roll;
}
}
CodePudding user response:
this
keyword doesn't refer to the class name. It refers to the current object. It's not a static
reference.
CodePudding user response:
See, you are making two constructors which has a default value of 13 and one which sets the value. To be more precise, the first constructor Student()
gets called if no value is given to it and calls the second constructor Student(int roll)
with a default value of 13.
Then coming to your question, we can refer from one constructor to another using this
For eg.
public class Car {
boolean isStart;
Car() {
this(true);
}
Car(boolean start) {
if (start == true)
isStart = true;
}
}
In this eg we see that if Car()
is called with default value this calls the other constructor with a boolean value.