I am learning inner class . Out of curiosity i extended the inner class which has a parameterized constructor. But when i write super(int i) to call it the code does not compile.
class Outer{
class Inner{
private int a;
Inner(int i){
this.a=i;
}
public void inheritFromInner(){
System.out.println("Inherited from inner");
}
}
}
class Test extends Outer.Inner{
Test(int r){
super(r);// This line does not compile.
}
}
As inner classes are part(member) of the outer class and they have to be accessed through the outer class. How the super constructor of Test class can be called.
The compile error is: No enclosing instance of type Outer is available due to some intermediate constructor invocation
The existing answers do not expound upon the differences among the kinds of member classes.
A member class is any class that is declared within another class. They are sometimes called nested classes. Of the kinds of member classes, anonymous inner classes and local classes will not be mentioned here. The remaining kinds of member classes are inner classes and static member classes.
Inner Class. An inner class instance must be instantiated with the context of an existing outer class instance. Inner classes contain an implicit reference to the outer class instance (a fact which can cause inner class instances to lead to memory leaks). Although uncommon, you can instantiate an inner class instance as follows:
Because the
super()
keyword must be the 1st line to execute within a subclass constructor, you would have to declare your constructor like this if it really does need to be in an inner class:Static Member Class. A static member class is declared with the modifer
static
in the class declaration. In almost every way that matters, a static member class is a top level class. Like top level classes (and unlike inner classes), they do not require any other object instances for instantiation. Static member class objects are commonly intantiated as:Whenever possible, you should strongly favor the use of static member classes over inner classes. Use inner classes only when your member class objects really must have a superclass instance (which should be uncommon).