Monday, June 16, 2008

Local and Anonymous Inner Classes in Java


Local and Anonymous Inner Classes in Java

If you want to refresh your understanding of inner classes then read this article first - Nested Classes & Inner Classes in Java >>

Local Inner Classes in Java

If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. A local inner class is not a member of the enclosing class and hence it can not have any access specifier. A local inner class will have access to all the members of the enclosing class and it'll have access to the local final variables in the scope it's defined.

Example: a typical local inner class

public class EnclosingClass{
...

public methodName(){
//...definition of the local inner class

class LocalInnerClass {
...
}
...
}

Anonymous Inner Classes in Java

If an inner class has been declared without a name and within a code block (typically within the body of a method) then such an inner class is called an anonymous inner class. Since such an inner class doesn't have a name associated, so it'll be accessible only at the point where it is defined.

Example: a very common usage of an anonymous inner class

public class GUI extends JFrame{
...
public void buildComponents(){
...
button1 = newJButton();
...
button1.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent ae){
...
...
}
});
...
...
}
}

Since, an anonymous inner class doesn't have a name, so it can't have a named constructor. But, it can have an instance initializer. Access rules for anonymous inner classes are same as that of local inner classes. Similar to a local inner class, an anonymous inner class can also not have any access specifier attached to it.

Are anonymous inner classes same as local inner classes?

Yeah..., an anonymous inner class is a local inner class in all means except that it doesn't have a name and hence it can't be used at any other point except at the point where it has been defined. The other difference is that it can't have a named constructor again for the same reason that it doesn't have a name.



Share/Save/Bookmark


3 comments:

SP said...

This was useful......thanks

Anonymous said...

Thanks...

Anonymous said...

Lovely! Thanks so much. Another good one here also:

Anonymous inner class example