一、Retail Application – Case Study
class Customer{
private int customerId;
private long telephoneNo;
public void setCustomerId(int customerId){
customerId = customerId;
}
public int getCustomerId(){
return customerId;
}
}
class Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
System.out.println("Customer Id:"+ custObj.getCustomerId());
}
}
Output:
Customer Id: 0
Why is the customerId not initialized to 1001?
The local variable in the setCustomerId() method hides the instance variable, customerId since they have the same name
In a class if the name of an instance variable is same as the local variable of a method then inside the method local variable hides the instance variable. This phenomena is known as instance variable hiding
二、Retail Application – Case Study
class Customer{
private int customerId;
private long telephoneNo;
public void setCustomerId(int customerId){
this.customerId = customerId;
}
public int getCustomerId(){
return customerId;
}
}
class Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
System.out.println("Customer Id:"+ custObj.getCustomerId());
}
}
Note the usage of this to prevent instance variable hiding
Output:
Customer Id: 1001