When a nested class in instantiated how does it reference the outer class? Does it always extend the outer class or reference it another way? I was told that the inner extends the outer but then why doesn't the following example work?
For 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 '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 show that the inner class does not extend the outer class unless specifically specified.
In Java programming, nested and inner classes often go hand in hand. A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.
In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.
Static Nested Class : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.
There is no implicit sub-type relationship: your observation/conclusion is correct. (In the first case, super
has the type of "Object" and "Object.fruit" does indeed not exist.)
An inner class (as opposed to "static nested class"), as shown, must be created within context of an instance of the outer class; but this is orthogonal to sub-typing.
To access a member of the outer class, use OuterClass.this.member
or, if member
is not shadowed, just member
will resolve; neither super.member
nor this.member
will resolve to the outer class member.
Extending the outer class "fixes" the compiler error, but the code with this.fruit
doesn't access the member of the enclosing OuterClass instance - it simply accesses the member of the InnerClass instance inherited from the superclass it extends.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With