Java
provides the concept of inner classes that is the classes defined within
another classes, or even within an expression.
For
understanding the benefits provided by inner classes, consider the applet shown
below:
import
java.awt.event.*;
import
java.applet.*;
import
java.awt.*;
public
class MyAdapterApplet extends Applet
{
public
void init()
{
addMouseListener(new
MyAdapter(this));
}
}
class
MyAdapter extends MouseAdapter
{
MyAdapterApplet
ap;
public
MyAdapter(MyAdapterApplet adp)
{
this.ap=adp;
}
public
void mouseClicked(MouseEvent e)
{
ap.showStatus("Mouse
Clicked");
}
}
In
the above example code, there are two top level classes: MyAdapterApplet &
MyAdapter. The same code can be improved by using inner classes as shown below:
import
java.awt.event.*;
import
java.applet.*;
import
java.awt.*;
public
class MyAdapterApplet extends Applet
{
public void init()
{
addMouseListener(new MyAdapter(this));
}
class MyAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
showStatus("Mouse
Clicked");
}
}
Anonymous Inner Class:
Anonymous inner class is one that is not assigned a name. The same applet code
shown above can be improved by using anonymous inner classes as shown below:
import
java.awt.event.*;
import
java.applet.*;
import
java.awt.*;
public
class MyAdapterApplet extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e)
{
showStatus("Mouse Clicked");
}
});
}
}
No comments:
Write comments