Tuesday, January 25, 2011

Inner classes and its magic

Inner classes have been bugging me for a long time and now I understood what they are.


For each class / interface it can be
top level OR Nested
Each nested class can be
Static OR Inner
Each Inner class can be
Member, Local or Anonymous.


Top level class

Its your normal class. Which has properties, methods, classes etc.
Nested Class

Class which is residing inside another class (or its method)
Static Inner Class

Acts same as Top level class and has package visibility.
Static inner class does not have package level visibility.

public class String{
private static class CaseInsensitiveComparator implements Comparator { ... }

The CaseInsensitiveComparator has only String class visiblity but does not require instantiations.

Member / Inner Class
Does not have package level visibility.
Outer class / enclosing class can not access variables without creating instance of the class.
Inner class can access the private variables of the outer class.
Gives more simplicity and object orientation. i.e. Car as outer, wheels as inner class.
Static fields / methods cannot be part of Inner Classes. Static can be part of only static or top level classes.

i.e.

class top{
int i = 22;

class myNested{
int k=i;
void food() {}

} // end of nested class

void doSomething(){
myNested mn = new MyNested()
mn.food();


}

} // end top

Local class

Example:

public class f extends Applet{

Button apple = new Button();

public void init () {

// Local class starts from here

Class InnerLocalClass implements java.awt.ActionListener {
int i=1;

public void ActionPerformed(Event e){
System.out.println("Somehting has happned ...");
} // end method

}// end inner local class

// Local class ends here

}// end init method

add(apple);
apple.addActionListener(new InnerLocalClass);

}// end class


Anonymous Classes

We saw that a method that has inner class and that is accessible by the enclosing class. Instance of Local Class is passes to action listener to track events. Now what if we can add the methods / implementation directly to any action listener.

i.e.

public class f extends Applet{

Button apple = new Button("Text Name");

public void init(){
int clickCount = 0;
add(apple);
apple.addActionListener(new ActionListener(){
public void ActionPerformed(ActionEvent e) { ... do something ... }
// you can add more listeners here
}
}
}

clickCount cannot be part of do something. Because it is not final. So when the code is compiled the clickCount is not passes to Inner Anonymous class unless it has final as access modifier.

How these classes are compiled altogether:
- Compiler creates outerclass$something for inner classes and created when compiled. For static they are treated as top level classes.

No comments:

Post a Comment