Strange compilation error with inner classes

The following code compiles as expected:

class A { class B {} class C extends B {} } 

But if we have a class B expand class A , we get a compilation error:

 class A { class B extends A {} class C extends B {} // <-- Error here } 
  No enclosing instance of type A is available due to some intermediate 
 constructor invocation.

What's going on here? Why does extension A change nothing?

EDIT: Apparently, this compiles in Java 7. I would like an explanation as to why it did not compile in older versions of Java and what was changed to Java 7 to allow this.


CM. ALSO:

+4
source share
2 answers

Since B not static, it needs some instance of A so that it can exist, therefore an error.

If B is static, the error disappears.

Oh, forget the bullshit. This is a bug , and it runs on ideone in Java7 mode. However, until Java 7, this did not work - see this question , and you need to either

  • Change B to static

  • Add Constructor

     C() { A.this.super(); } 

And then it will work.

The reason this happens before Java 7 may be the following is from JLS:

Let C be an instance of the class, S be the direct superclass of C, and I be the instance to be created.

The implicit super is invoked in the immediate incoming instance of I with respect to S.

In earlier JLS, an instance that directly includes is defined as

Let O be the innermost lexically encompassing class, S be a member, and n be an integer such that O is the nth lexically encompassing class C. The instantly included instance i in S is the nth lexical encompassing instance of this.

However, in Java 7 :

Let O be the innermost lexically encompassing class S, n be an integer such that O is the nth lexically encompassing class C.

The instance i included in the instance of S is the nth lexically encompassing instance of this.

Thus, in the past it was the innermost lexically encompassing class, S is a member , and now it is the most lexically encompassing class S , so it has changed from C to A , so the code works in Java 7.

+5
source

This is recursion.
If B continues A, and A has a new B on its own, so B continues A again and so on ...

As @ZiyaoWei already mentioned, the error disappears when B is static . This is because then class B will exist only once.

+1
source

Source: https://habr.com/ru/post/1486032/


All Articles