In Java not all classes must be described separate from each other. You may put the definition of one class under the definition of another class. The class inside class is called an inner class and the enclosing class is called an outer class. So when you prepare an inner class, it is a member of the outer class in much the similar way as other members like attributes, constructors and methods.
Where should we need inner classes? Code without inner classes is hard to maintainable and readable. When you use private data members of the outer class, the JDK compiler provides package-access member functions in the outer class for the inner class to use the private members. That leaves a security hole. We could avoid it using inner classes. Use inner class only when an inner class is only in the context of the outer class and/or inner class may be prepared private so that only outer class can access it. Inner classes are needed primarily to implement helper classes like Comparators, Iterators etc which are needed in the context of an outer class.
Member inner class
|
Anonymous inner class
|
public class MyStack {
private Object[] items = null;
...
public Iterator iterator() {
return new StackIterator();
}
//inner class
class StackIterator implements Iterator{
...
public boolean hasNext(){...}
}
}
|
public class MyStack {
private Object[] items = null;
...
public Iterator iterator() {
return new Iterator {
...
public boolean hasNext() {...}
}
}
}
|
Class Type
|
Description
|
Example +
|
Class name
|
|
Outer
class
|
Package
member class or interface
|
Top level class. Only type JVM
can access.
|
//package scope
class Outside{}
Outside.class
|
Inner
class
|
static nested
class or interface
|
Defined within the context of the
top-level class. Must be static & can access static members of its having class. No relationship between the instances of outside and Inside classes.
|
//package scope
class Outside {
static class Inside{ }
}
Outside.class ,Outside$Inside.class
|
Inner
class
|
Member class
|
Defined within the context of
outer class, but non-static. Until an object of Outside class has
been started you can't create
Inside.
|
class Outside{
class Inside(){}
}
Outside.class , Outside$Inside.class
|
Inner
class
|
Local class
|
Defined within a part of code.
Can use final local variables and final method parameters. Only
visible within the part of code that defines it.
|
class Outside {
void first() {
final int i = 5;
class Inside{}
}
}
Outside.class , Outside$1$Inside.class
|
Inner
class
|
Anonymous
class
|
Just like local class, but no
name is used. Useful when only one instance is used in a
method. Most naturally used in
AWT/SWING event model, Spring framework hibernate call
back methods etc.
|
//AWT example
class Outside{
void first() {
button.addActionListener ( new ActionListener()
{
public void actionPerformed(ActionEvent e) { System.out.println("The button was pressed!");
}
});
}
}
Outside.class , Outside$1.class
|