Sunday, September 20, 2009

Calling new on an object

When can we call a new on an object? We normally use a new keyword in java to create a new object as follows:
Integer i = new Integer();
But can we use the new keyword on an object itself as follows:
TestClass.MyClass c = new TestClass().new MyClass();

This is the syntax of creating an inner class instance. Its only in this case that we use the new operator on an object. To create an inner class instance we need to have an outer class instance in place. See the following code which represents a simple regular inner class

public class TestClass {
private String s = "Hello World";
  public class MyClass{ // inner class
   public void go(){
     System.out.prinln(s);
   }//end of inner class method
  }// end of inner
}// end of outer

If you notice that in the above piece of code the inner class is accessing the outer class private variable. This is allowed because the inner class shares a special relationship with the outer class which allows the inner class to directly access the outer class variable even if they are private. The new operator can be used on an object only in the case of inner classes.

The above example shows only a regular inner class. There are some more types of inner classes which are method specific inner class, arguement specific inner class and static inner class. These types will be explained in later posts.