码家

Web Platform, Cloud and Mobile Application Development

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一、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

ØImplicit reference to refer the current object, i.e the object which invoked the method
ØUsed to resolve ambiguity between instance variables and local variables when they have the same name, i.e it prevents instance variable hiding
Ø‘this’ reference can be used in some cases to improve the readability of a program

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

posted on 2011-05-21 15:51  海山  阅读(152)  评论(0)    收藏  举报