Can someone please explain output 0 in case of first constructor without this ?
If the argument variable name is same as class property name and i am using that property inside the method. What does java interpret that “class property” or “the argument variable” ?
Without this:
public User(int userId){
userId = userId;
}
With this:
public User(int userId){
this.userId = userId;
}
public void PrintUserId(){
System.out.println(this.userId);
}
User firstUser = new User(123);
firstUser.PrintUserId();
// 0 without this
//123 with this
Sure – this statement is a no-op:
It just assigns the variable of the
userIdparameter to itself. It doesn’t touch the field at all. Within the method, the parameteruserIdshadows the field calleduserId– so you have to explicitly say that you want to refer to the field, which is what the second version does:I’d expect any modern IDE to highlight the no-op assignment in the first version with a warning.
(It’s worth being clear about terminology, by the way – an argument is a value provided to a method; a parameter is the variable which is declared as part of the method signature. Likewise it’s a field rather than a property.)
EDIT: If the parameter has a different name, e.g.
then the parameter doesn’t shadow the field, and the identifier
userIdstill refers to the field. It’s all a matter of working out what the meaning of an identifier is – in your first example, the simple nameuserIdrefers to the parameter, which is what causes the problem.EDIT: From section 6.4.1 of the JLS:
So in this case d would be the declaration of the formal parameter
userId, and the scope of d is the constructor – so throught the constructor, the parameter shadows the field.