Wednesday 29 February 2012

Inner Classes


What is inner class and what are types of inner classes

Inner class is a class which is defined in other class or method. Inner class shares special relationship with outer class. As inner class is defined within class it can access private variables of outer class

There are four types of inner classes

                1) Member Inner Class: First outer class instance needs to be created then inner class instance is created on outer class instance .i.e new Outer().new Inner();

2) Static Inner Class: To access static inner class we don’t need to create instance of outer class. Static inner class can be directly accessed as static variables of class. i.e. new Outer. Inner();

3) Method local Inner Class: These classes are defined within method

4) Anonymous Inner Class: Anonymous inner classes are created and instantiated on the fly. They don’t have any name. They can’t use keywords like extends or implement. Therefore they can either subclass of any class or implementer of any interface. They are terminated with semicolon.

e.g.

Runnable myRunnable=new Runnable(){

public void run()

{

}

};

We can define new methods in inner class, but due to polymorphism we can only call methods defined in supertype reference either interface or class

Anonymous inner class can be passesd as arguments to methods




No comments:

Post a Comment