No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer)
I didn’t find this problem when I looked at the internal class before. I encountered this problem when I was writing code today. Let’s write the simplest example:
Here’s the code
The red part is the compilation error:
No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer).
According to the prompt, there is no instance outer that can be accessed, and a suitable outer class instance must be assigned to access the inner class
The correct way can be:
public class Outer {
private int i = 10;
class Inner{
public void seeOuter(){
System.out.println(i);
}
}
public static void main(String[] args) {
Outer out = new Outer();
Inner in = out.new Inner();
in.seeOuter();
}
}
Or:
public class Outer {
private int i = 10;
static class Inner{
public void seeOuter(){
// Static internal classes cannot access non-static members of external classes directly, but they can be accessed by means of new external class(). member
//System.out.println(i);This sentence does not compile
System.out.println(new Outer().i);
}
}
public static void main(String[] args) {
Inner in = new Inner();
in.seeOuter();
}
}
About inner classes
It is still an independent class. After compilation, the internal class will be compiled into an independent. Class file, but it is preceded by the class name and $symbol of the external class
Inner classes cannot be accessed in the normal way. The inner class is a member of the outer class, so the inner class can freely access the member variables of the outer class, whether it is private or not
No static declaration is allowed in member inner class
The only way to access a member’s inner class is through the object of the outer class