Inner Classes

Creating Inner Classes Instances

Non-static inner classes have a hidden reference to the enclosing class instance. This means you must have an instance of the enclosing class to create the inner class. You also have to use a special "new" function that correctly initializes the hidden reference to the enclosing class. The special "new" function is a member of the enclosing class.

public class InnerClassTest {	
	public class ReallyInner {	    
	}	
}
					
					
InnerClassTest o = new InnerClassTest();
InnerClassTest.ReallyInner i = o.new ReallyInner();
					
or
InnerClassTest.ReallyInner i = new InnerClassTest().new ReallyInner();
					

Example:

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.ReallyInner i = new InnerClassTest().new ReallyInner();
	        i.test();
	}
}
					
					
Output:
Inner class
Outer class