0

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

Simon
  • 41
  • 6
  • 1
    The `this` keyword distinguishes your class members from the parameters in your constructor having the same names. Otherwise, how can Java tell which ones you are referring to? Java isn't smart enough to divine your intent here, and `rollnumber = rollnumber;` doesn't make much sense anyway. – Robert Harvey Aug 19 '20 at 19:52
  • Great, that helps my understanding ! Thanks a ton. I tried naming the variables diff to the parameter names and it worked, without "this". – Simon Aug 19 '20 at 19:58
  • Java programming conventions use camelCase. For instance, the variable should be named rollNumber. – NomadMaker Aug 19 '20 at 20:36

1 Answers1

0

let’s keep constructors aside and just look at it from a code point of view.

the parameters rollnumber and name are local variables, their scope is only in the function. So when you say

rollnumber = rollnumber;

It simply assigns the current value of local variable rollnumber to itself (does nothing). There is no way to differentiate rollnumber (the parameter/loca variable inside the function) and the instance variable, rollnumber.

To make sure the compiler understands what we want, we use

this.rollnumber (referring to instance variable) = rollnumber (parameter);

To avoid this, you can name your instance variable something else, like rollnum. This way the compiler will search for rollnum in the local scope (meaning within the constructor function, not found) then in the higher scope, where it will be found as an instance variable and correctly assigned.

 rollnum = rollnumber;

will work.

srv236
  • 509
  • 3
  • 5
  • srv236 Thanks. I tried it before reading this and it does work.Your explanation definitely simplifies the way to look at it. – Simon Aug 19 '20 at 20:04