I'm very new to JAVA and trying the following code to initialize the values of object variable using constructor:
public class Javaprog {
int rollnumber;
String name;
Javaprog(int rollnumber, String name) {
rollnumber = rollnumber;
name = name;
}
public static void main(String[] args) {
Javaprog student1 = new Javaprog(12, "Simon");
System.out.println(student1.rollnumber);
System.out.println(student1.name);
}
}
I want to understand why the code above returns the default values of rollnumber and name(0 and null), unless I use "this" to reference the variables inside the constructor like below:
this.rollnumber = rollnumber; this.name = name; I'm aware this refers to the current object, but my point is when the constructor runs for creation of an object, does it not understand by default that these variables relate to the object being created .
Is it that, without the use of this keyword they are just "class variables" and don't attach to the object being created.
Found a similar Q here, but did not fully understand the mandate to use this: java this keyword inside constructor