Profess Physics
Profess Physics

Reputation: 317

Accessing outer class from within inner class using outerClass.this

The -non-static- inner class has a full accessibility to all regular members of the outer class. but there is another way to access these members using the (outerClass.this.regularMember).., have a look on the following code:

public class Car {
  int x = 3;
  public static int hp =6;
  public void move()
  {
    System.out.println(hp);
  }

  public  class Engine{
     public int hp =5;
     public int capacity; 
     public void start()
     {
        Car.this.move(); // or we can use only move();
     }

  }
}
  1. Could you please explain me if there would be any practical difference between using Car.this.move(); and move();
  2. How can you explain this syntax of Car.this. , cause as far as I understand this here refers to an object of Type Engine but then if I used another reference say by doing Engine smallEngine = new Engine();then this keyword is not substitutable by smallEngine .

Upvotes: 1

Views: 237

Answers (1)

john16384
john16384

Reputation: 8044

  1. If your Engine class has a move method, then move() would be different from Car.this.move().

  2. this means the current instance. When you want to refer to the outer class, you are allowed to qualify the this keyword with the outer class to refer to the outer class's instance. The important thing to remember is that an instance of Engine (since it is not static) is always accompanied by an instance of Car and so you can refer to it.

You are not allowed to say OuterClass.smallEngine.move() because that would conflict with the syntax for accessing a static public field of OuterClass.

If OuterClass had a field like this:

 public static String smallEngine;

...then the above syntax would be ambigious. Since this is a keyword, you cannot have a field named this and therefore the syntax OuterClass.this will never be ambigious.

Upvotes: 3

Related Questions