Why can't I access the inner class in Java?

I'm having trouble using nested classes in Java, does anyone know why Java doesn't allow me to do this?

public class A{
    private class B{
        public B(){
            System.out.println("class B");
        }
    }

    public static void main(String[] args){
         A a = new A();
         B b = new B();
    }
} 
+4
source share
4 answers

Because you are trying to access a non-stationary inner class from a static method.

The first solution is to change your inner class Bto static:

public class A{
    private static class B {
        public B() {
            System.out.println("class B");
        }
    }

    public static void main(String[] args){
         A a = new A();
         B b = new B();
    }
}

A staticinner class is accessible from anywhere, but non-static, requires an instance of your container class.

Another solution would be:

A a = new A();
B b = a.new B();

, Java: http://www.javaworld.com/article/2077411/core-java/inner-classes.html

+8
A a = new A();
B b = a.new B();

. A?

public class JustForShow {
    public class JustTry{

        public JustTry() {
            System.out.println("Initialized");
        }
    }
    public static void main(String[] args) {
        JustForShow jfs = new JustForShow();
        JustTry jt = jfs.new JustTry();
    }
}
+7

membor . , :

  • B , static , :

    public static class B { // ...
    
  • a B, :

    B b = a.new B();
    

If Bnot using non-static class resources a, I would recommend using the first method.

+4
source
public static void main(String[] args){
     A a = new A();
     A.B b = a.new B();
}
+1
source

All Articles