St.Antario
St.Antario

Reputation: 27375

Inner class constructor invocation

The JLS says:

The constructor of a non-private inner member class implicitly declares, as the first formal parameter, a variable representing the immediately enclosing instance of the class.


Ok, if we write the following:

class A:

package org.gradle;

public class A extends B.Inner{

    public A(B b){
        b.super();        //OK, invoke B.inner(B)        
    }
}

class B:

package org.gradle;

public class B{

    public class Inner{
    }
}

As said here, b.super() actually invoke B.Inner(B).


But if we write

class B:

package org.gradle;

public class B {
    class Inner{ 
        public Inner(B b){
            System.out.println("Inner(B)");
        }
    }
}

class A:

package org.gradle;

public class A extends B.Inner{

    public A(B b) {
        b.super(); //The constructor B.Inner() is undefined
    }
}

So, in the latter example b.super() tries to invoke B.Inner() instead. Why is that so difference?

Upvotes: 0

Views: 127

Answers (1)

It does try to invoke B.Inner(B) in your second example.

It can't find it because there's only a B.Inner(B, B). If your constructor is B.Inner() then it gets changed to Inner(B)... and if your constructor is B.Inner(B) then it gets changed to B.Inner(B, B).

Note that the hidden parameter is effectively an implementation detail, and unless you're studying how the Java compiler works, you don't need to know it exists.

Upvotes: 3

Related Questions