There is no instance of an instance of type ... in scope

I am exploring the inner classes of Java.

I wrote an example:

public class Outer { public Outer(int a){} public class Inner { public Inner(String str, Boolean b){} } public static class Nested extends Inner{ public static void m(){ System.out.println("hello"); } public Nested(String str, Boolean b , Number nm) { super("2",true); } } public class InnerTest extends Nested{ public InnerTest(){ super("str",true,12); } } } 

I call it from main using the following line:

  new Outer(1).new Inner("",true); 

I see a compilation error:

  java: no enclosing instance of type testInheritancefromInner.Outer is in scope 

Can you explain this situation to me?

UPDATE

enter image description here

+7
java inheritance instantiation inner-classes
source share
2 answers

Inner is an inner class. It can only be created when there is an instance of the class containing the definition of the Inner class.

However, you created a static nested Nested class that extends from this class. When you try to call a super constructor

 public Nested(String str, Boolean b , Number nm) { super("2",true); } 

it will not work because the superstructor for Inner depends on an Outer instance that does not exist in the static context of the Nested class. Jon Skeet provides a solution.

An explanation of the solution appears in JLS here .

Superclass constructor calls can be split:

  • Unqualified calls to the superclass constructor begin with the super keyword (possibly preceded by an explicit type argument).

  • Qualified superclass constructor calls start with a Primary expression.

    • They allow the subclass constructor to explicitly indicate a newly created object that immediately includes an instance with respect to the direct superclass (ยง8.1.3). This may be required when the superclass is an inner class.
+13
source share

As Sotirios said, your nested (non-inner) class does not have an implicit Outer instance to effectively provide Inner .

You can get around this, however, by explicitly specifying it before the .super part:

 public Nested(String str, Boolean b, Number nm) { new Outer(10).super("2", true); } 

Or even take it as a parameter:

 public Nested(Outer outer) { outer.super("2", true); } 

However, I highly recommend that you avoid such complex code. In most cases, I avoid nested classes, almost always call inner classes, and I can never remember how they fit with them.

+14
source share

All Articles