Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not access an inner class in Java? [duplicate]

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();
    }
} 
like image 525
Rogger Fernandes Avatar asked Dec 01 '22 01:12

Rogger Fernandes


2 Answers

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

like image 151
Victor2748 Avatar answered Dec 05 '22 14:12

Victor2748


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();
    }
}
like image 38
Gurkan İlleez Avatar answered Dec 05 '22 12:12

Gurkan İlleez