Reputation: 317
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();
}
}
}
Car.this.move();
and move();
Engine smallEngine = new Engine();
then this keyword is not substitutable by smallEngine . Upvotes: 1
Views: 237
Reputation: 8044
If your Engine
class has a move
method, then move()
would be different from Car.this.move()
.
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