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?