Inner Classes

Inner Classes are the classes which are declared inside an outer class i.e classes nesting with in outer class. They can be either static or non static. Static Inner classes are also called as Nested Classes. Inner classes come in Four flavors namely:
Inner Classes

1. Static Member Classes
2. Member Classes
3. Local Classes
4. Anonymous classes

Static Member Classes: A Static Member Class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes: A Member Class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent’s this reference.

Local Classes: Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

Code Snippet (Taken From Core Java, Vol-1, By Cay S. Horstmann, Gary Cornell)

public void start()
{
class TimePrinter implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println(“At the tone, the time is ” + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
}

ActionListener listener = new TimePrinter();
Timer t = new Timer(1000, listener);
t.start();
}

Anonymous Classes: An Anonymous Class is a local class that has no name.

Code Snippet (Taken From Core Java, Vol-1, By Cay S. Horstmann, Gary Cornell)

public void start(int interval, final boolean beep)
{
ActionListener listener = new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Date now = new Date();
System.out.println(“At the tone, the time is ” + now);
if (beep) Toolkit.getDefaultToolkit().beep();
}
};
Timer t = new Timer(1000, listener);
t.start();
}

I have given specific examples for Local and Anonymous Classes because they are pretty different from the usual style of declaring classes and Anonymous Classes are very useful in adding developing GUI’s.

I have here given just the outline for Inner Classes.Visit the links given below and the bool i have mentioned for detailed information on Inner Classes with ample examples.

For more details on Inner Classes and their advantages can be obtained from the following links:

Java Ranch-Getting in Touch With your inner Class
Java World-Inner Classes
Core Java, Volume 1, By Cay S. Horstmann, Gary Cornell

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading