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();
}
}
}
- Could you please explain me if there would be any practical difference between using
Car.this.move();andmove(); - 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 .
If your
Engineclass has amovemethod, thenmove()would be different fromCar.this.move().thismeans the current instance. When you want to refer to the outer class, you are allowed to qualify thethiskeyword with the outer class to refer to the outer class's instance. The important thing to remember is that an instance ofEngine(since it is not static) is always accompanied by an instance ofCarand 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 ofOuterClass.If
OuterClasshad a field like this:...then the above syntax would be ambigious. Since
thisis a keyword, you cannot have a field namedthisand therefore the syntaxOuterClass.thiswill never be ambigious.