Monday, April 16, 2012

Java this.classProperty versus classProperty incase argument variable name clashes?

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





No comments:

Post a Comment