Class nested in Java

10

I need to have nested classes in Java. Why does not the following implementation work?

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();
    }
} 

In the line I try to instantiate the inner class B, the following error occurs:

  

No enclosing instance of type A is accessible

    
asked by anonymous 20.10.2014 / 21:42

2 answers

3

You can not instantiate directly as you did. A reference is required for the parent class so before you need to create an instance for it and in this instance access the inner class. Here's an example I took of a tutorial on inner classes :

public class InnerClassTest {
    public void foo() {
        System.out.println("Outer class");
    }

    public class ReallyInner {
        public void foo() {
            System.out.println("Inner class");
        }

        public void test() {
            this.foo();
            InnerClassTest.this.foo();
        }
    }

    public static void main(String[] args) {
        InnerClassTest o = new InnerClassTest();
        InnerClassTest.ReallyInner i = o.new ReallyInner();
        i.test();
    }
}

I placed GitHub for future reference .

    
20.10.2014 / 21:52
5

Your code does not work because you are trying to access a non-static member of A (the nested class B ) from a static method ( static main ); and you can only access non-static members of a class from an instance of the class.

So for your code to work, you have 3 options:

Instantiate B from an instance of A :

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 = a.new B(); // instância de B a partir de uma instância de A
    }
} 

Change the main method to non-static, since if it is an instance method, you have access to non-static members of your class:

public class A{
     private class B{
        public B(){
            System.out.println("class B");
        }
    }
    // instância de B a partir de um método não estático de A    
    public void doSomething(String[] args){ 
        // A a = new A();
         B b = new B();
    }
} 

Or declare B as static class, so it is accessible from static members (in this case, the main method).

public class A{
     // B declarado como classe estática
     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();
    }
} 

Update: In the second example, I changed the method name to not be confused as input method of a Java main class, because to do so it would need to be static. This code has only the didactic role on nested classes.

    
20.10.2014 / 22:05