2

I've seen two ways of instantiating inner classes. For example

class OuterClass{
    private int x = 23;

    class InnerClass{
        public void printX(){
            System.out.println(x);
        }
        public void printStuff(){
            System.out.println("This is an inner class method");
        }

    }
}

public class TestMain321{
    public static void main(String[] args){
        OuterClass o = new OuterClass();
        OuterClass.InnerClass i = o.new InnerClass();
        i.printX();
    }
}

And

class OuterClass{
    private int x = 23;
    InnerClass i = new InnerClass();
    public void innerMethod(){
        i.printX();
    }

    class InnerClass{
        public void printX(){
            System.out.println(x);
        }
        public void printStuff(){
            System.out.println("This is an inner class method");
        }

    }
}

public class TestMain123{
    public static void main(String[] args){
        OuterClass o = new OuterClass();
        o.innerMethod();
        i.printStuff();//WON'T COMPILE

    }
}

One the first example, I can call the inner class method directly because I'm instantiating the inner class in main()

OuterClass.InnerClass i = o.new InnerClass();
i.printX();

The difference is that on the 2nd example, I'm instantiating the inner class directly inside the outer class, so later in the main method I cannot call a method of the inner class directly, since it doesn't know the reference. I have to create an outer class method to call the inner class method, for example see the innerMethod() in the outer class.

public void innerMethod(){
            i.printX();
        }

Are there any other reason why I'd implement one way versus the other? Is there a best practice on how this should be done?

Pablo Gonzalez
  • 1,710
  • 3
  • 21
  • 36

1 Answers1

4

Your inner classes should always be private to prevent outside access except for outer class. This is mentioned in Effective Java Book and this question.

  1. "An inner class should exist only to serve its outer class."

If your inner class needs to be public, seriously consider making it normal class in its own right instead of inner class.

Community
  • 1
  • 1
Atilla Ozgur
  • 14,339
  • 3
  • 49
  • 69