Nick Nick Nick Nick - 1 year ago 78
Java Question

Inheriting from inner class


public class A {
public A() {

public class B {
public B() {
class Caller extends A.B {
Caller(A a){

public class Main {
public static void main(String[] args) {
Caller as= new Caller(new A());

Why do we need
call in class extending inner class? What does it doing?
program does not want to compile!

Error:(48, 20) java: an enclosing instance that contains A.B is required

Answer Source

The answer is: because that's how it is specified in the Java Language Specification.

Your class A.B is an inner class of A. The constructor has a hidden argument of type A - the enclosing (outer-class) instance.

You have subclassed A.B in your class Caller, which is itself not an inner class. But the constructor of the superclass needs this hidden instance of A - the outer class instance.

The way in which you pass this in Java is using this a.super(); syntax.

The Java Language specification defines this in section

Qualified superclass constructor invocations begin with a Primary expression or an ExpressionName. They allow a subclass constructor to explicitly specify the newly created object's immediately enclosing instance with respect to the direct superclass (ยง8.1.3). This may be necessary when the superclass is an inner class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download