'How does referring to class name through 'this' keyword while calling another constructor from a constructor set values to an object? [closed]
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;
}
}
Solution 1:[1]
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.
Solution 2:[2]
this keyword doesn't refer to the class name. It refers to the current object. It's not a static reference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | theaniknath |
| Solution 2 | Chetan Ahirrao |
