Explain the functioning of “this” Keyword and the concept of Instance Variable Hiding by using “this” keyword in java [closed]

99封情书 提交于 2019-12-11 18:24:01

问题


I have been learning Java from Java 2: Complete Reference, 5th Edition. I couldn't understand the exact of purpose this keyword and the concept of instance variable hiding. please explain me with example.


回答1:


The exact purpose of this is to remove ambiguity from local variable from your field variables.

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):

class Foo
{
 private int bar; 

 public Foo() {
      this(42); // invoke parameterized constructor
 }

 public Foo(int bar) {
     this.bar = bar; // disambiguate 
 }

 public void frob() {
      this.baz(); // used "just because"
 }

 private void baz() {
      System.out.println("whatever");
 }

}

also read this keyword and also this link



来源:https://stackoverflow.com/questions/20857771/explain-the-functioning-of-this-keyword-and-the-concept-of-instance-variable-h

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!