简体   繁体   中英

How does an explicitly scoped this keyword in java work?

I know this key word is used to point to current class fields and to call constructor like:

class A{
String name;
  public A(String name)
  {
   this.name=name;
   this.(name.length());
  }

  public(int len)
  {
   //some code here
  }
}

but my I recently came across:

class B extends A
{
A varA = B.this;
} 

I don't understand how B.this works. can any one elaborate in detail

B.this is a reference to B class instance.

as B extends A it is possible to declare a variable of type A and assign it to a reference to B class instance.

In the example you have, B.this is equivalent to this , so it's not very illustrative. Scoped this declarations are far more valuable when you start working with inner classes....

class Outer {
  public void doSomething() {
  }

  class Inner {
    public void doSomething() {
      Outer.this.doSomething();
    }
  }
}

Notice the use of Outer.this in the Inner class. Without it, the inner class would have no way of disambiguating between the this that referred to the Inner instance and the this that referred to the Outer instance.

The B.this means that you are getting the reference/pointer of the B class instance, B inherits from A so what you are actually doing is Initializing your A with the reference/pointer of B .

The B.this is useful when you are calling the instance of B class inside a anonymous/inner classes.

You can also call this which is equivalent to B.this but you cant call this in a anonymous/inner classes or else you'll get the instance of them not the class B instance.

In fact, the this keyword is used to refer to the instance of a class.

When you do

this.name

you are referring to the attribute name from the actual instance of the class A .

When you do

B.this

you are referring to the B class intance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM