ajb ajb - 10 months ago 56
Java Question

What rule prohibits this nested class reference?

I know this is illegal, but I haven't been able to find the rule(s) in the JLS that make it so. I've scoured Chapter 8 but haven't found anything.

public class C1 {
public class C2 {

public class C3 extends C1.C2 {

from the command line gives me "an enclosing instance that contains C1.C2 is required"; Eclipse says "No enclosing instance of type C1 is available due to some intermediate constructor invocation".

What language rules make this illegal, exactly? [Note: There are a number of StackOverflow questions about this error message, but the ones I've seen all involve an error on a
; I'm asking why the class declaration is itself illegal.]

As a side question, is there any inherent reason why this needs to be illegal? It seems like things would work as long as
was always constructed with
x.new C3(...)
is a
(or subclass). Is there some other case that would cause problems if this class definition were allowed?

Answer Source

Because C2 is an inner class of C1, it is constructed bound to an instance of C1, but C3 is not enclosed by C1, so it does not by default have access to an instance of C1 to pass to its parent C2's constructor. It needs an explicit constructor that will provide an instance of C1 to C2:

public class C3 extends C1.C2 {
    public C3(C1 outer) {

The syntax outer.super() is called a qualified superclass constructor invocation.

This isn't necessary if C2 is made static.