Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

java - no enclosing instance of type... in scope

I investigate java inner classes.

I wrote 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 invoke it from main using following string:

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

I see compile error:

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

Can you explain me this situation?

UPDATE

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Sotirios has said, your nested (not-inner) class doesn't implicitly have an instance of Outer to effectively provide to the Inner.

You can get round 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 accept it as a parameter:

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

However, I would strongly advise you to avoid such convoluted code. I avoid nested classes most of the time, named inner classes almost always, and I can't ever remember using a combination of them like this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...