4

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();
    }
} 
Victor2748
  • 4,149
  • 13
  • 52
  • 89
  • You should not use inner classes in first place :). Do you really need it? – libik Oct 20 '14 at 19:50
  • 1
    @libik: There's nothing wrong with inner classes, but like most features of a language, you can abuse it. – Makoto Oct 20 '14 at 19:51
  • Just a thought... always include the type or error that you are experiencing as well when posting questions. – cp5 Oct 20 '14 at 19:52
  • @Makoto - well there is nothing wrong with `instanceof` or `singleton` pattern, but it usually means bad design, if you need it. – libik Oct 20 '14 at 19:54

4 Answers4

8

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

Victor2748
  • 4,149
  • 13
  • 52
  • 89
7
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();
    }
}
Gurkan İlleez
  • 1,503
  • 1
  • 10
  • 12
4

You are trying to access a non-static membor from a static method. To solve that, you have two options:

  1. Change your class B to be static, so add the static keyword in the class definition, like this:

    public static class B { // ...
    
  2. Change your main method, and use the created instance a to create B, like this:

    B b = a.new B();
    

If B doesn't use any non-static resources of class A, I would recommend to use the first method.

msrd0
  • 7,816
  • 9
  • 47
  • 82
1
public static void main(String[] args){
     A a = new A();
     A.B b = a.new B();
}
Schroed
  • 194
  • 10