Possible Duplicate:
Java inner class and static nested class
What are the uses of inner classes in Java? Are nested classes and inner classes the same?
Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.
In Java programming, nested and inner classes often go hand in hand. A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
Inner classes are used for various purposes, such as to create an instance of an object that is associated with the outer class, or to access members of the outer class. In general, inner classes are used to improve the organization and readability of code.
The difference is well addressed by the other answer. Regarding their usage/relevance, here is my view:
They are handy to implement callbacks easily, without the burden to create new named class.
button.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e ) {
frame.dispose();
}
}
);
They are also handy for threading (e.g. anonymous Runnable
) and a few other similar pattern.
Static nested classes are essentially like regular classes, except that their name is OuterClass.StaticNestedClass
and you can play with modifier. So it provided some form of encapsulation that can not exactly be achieved with top-level classes.
Think for instance of a LinkedList
for which you would like the class Node
(used only internally) to not be visible in the package view. Make it a static nested class so that it's fully internal to the LinkedList
.
An instance of an inner class has access to the field of its enclosing class instance. Think again of the linked list and imagine Node
is an inner class:
public class LinkedList {
private Node root = null;
public class Node {
private Object obj;
private Node next;
...
public void setAsRoot() {
root = this;
}
}
public Node getRoot() {
return root;
}
public void setRoot( Node node ) {
root = node;
}
}
Each Node
instance belonging to a LinkedList
can access it directly. There is an implicit ownership relationship between the list and its nodes; the list owns its nodes. The same ownership relationship would require extra code if implemented with regular classes.
See Achieve better Java code with inner and anonymous classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With