In Java, what is the relationship between a nested class and its outer class?

When a nested class instance is created, how does it refer to the outer class? Does it always propagate the outer class or refer to it in another way? I was told that the internal extension is external, but then why the following example does not work?

Example:

public class OuterClass { public String fruit = "apple"; public class InnerClass { public String fruit = "banana"; public void printFruitName(){ System.out.println(this.fruit); System.out.println(super.fruit); } } } 

The above does not compile with an error for super.fruit saying that the "fruit" cannot be resolved. However, if the inner class is specified to extend the outer class, then it works:

 public class OuterClass { public String fruit = "apple"; public class InnerClass extends OuterClass { public String fruit = "banana"; public void printFruitName(){ System.out.println(this.fruit); System.out.println(super.fruit); } } } 

This seems to indicate that the inner class does not extend the outer class unless specifically indicated.

+7
java reference inner-classes nested nested-class
source share
1 answer

There is an implicit subtype relation: your observation / conclusion is correct. (In the first case, super is of type "Object" and "Object.fruit" does not really exist.)

the inner class (as opposed to the "static nested class"), as shown, must be created in the context of the instance of the outer class; but it is orthogonal to imprinting.

To access a member of an outer class, use OuterClass.this.member or, if member not obscured, only member will be allowed; neither super.member nor this.member will be allowed to an external member of the class.

The extension of the outer class "fixes" the compiler error, but the code with this.fruit does not have access to the member of the incoming OuterClass instance - it simply refers to the member of the InnerClass instance inherited from the superclass that it extends.

+8
source share

All Articles