I am learning inner and outer classes in Java. I know what inner and outer classes are and why they are used. I came across the following question on this topic and could not find an answer.
Suppose the following code is given:
class outer{
class inner{
}
}
class SubClass extends outer.inner{
}
Question: How should the minimal subclass constructor be defined? and why?
Option 1-
Subclass () {
//reason: bacause the default constructor must always be provided
}
Option 2-
Subclass (Outer outer) {
//reason : because creating an instance of **Subclass** requires an instance
//of outer, which the **Subclass** instance will be bound to
}
Option 3-
Subclass (Outer outer) {
outer.super();
//reason : because creating an instance of **Subclass** requires an explicit
//call to the **Outer's** constructor, in order to have an enclosing instance
//of **Outer** in scope.
}
Option 4-
Subclass (Outer.inner inner) {
//reason : bacause an instance of **inner** is necessary so that there is a
//source to copy the derived properties from
}
PS. This is a multiple choice question. Only 1 answer is expected
i am new to java and don't know much about these advanced topics
Thanks
Here is an example from the JLS that follow this same logic but by not passing the enclosing instance but by creating it directly in the constructor :
The case the nearest in proposed answers is
To extend
Outer.Inner
that is an inner class ofOuter
,SubClass
constructor needs to have an instance ofOuter
that is the enclosing type.outer.super();
will invoke the constructor of theOuter
parent class that is theInner
constructor.The
outer.super();
syntax may be disconcerting as we don't invoke generallysuper()
on a parameter of a constructor but in the case of a class extending a inner class, the constructor of the subclass allows this syntax.