this reference

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值