I am having a trouble using nested classes in Java, does anyone know why Java does not allow me to do it?
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();
    }
} 
                Because you are trying to access a non-static inner-class from a static method.
The 1st solution will be to change your inner-class B to 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 static inner-class is accessible from anywhere, but a non-static one, requires an instance of your container class.
Another solution will be:
A a = new A();
B b = a.new B();
This will give you a better understanding of how inner classes work in Java: http://www.javaworld.com/article/2077411/core-java/inner-classes.html
A a = new A();
B b = a.new B();
can solve your problem
You used private inner class.How can you get instance outside the A class?
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();
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With