Why java has 'Static Inner Classes'? what is the real world use of it? what designer might gave thought when they added this capability? [duplicate]
Possible Duplicate:
Are static inner classes a good idea or poor design?
Java supports static inner classes, what the designer of language must have thought when they added it, what real world issues it solves?
Static inner classes are useful when you want the inner class to be "logically scoped" within the outer class (i.e. because it is closely related to the outer class and does not make sense on its own), but don't need the "code scope" features of regular inner classes i.e. there are no private fields or methods of the outer class that the inner class needs to access, and instances of the inner class don't logically belong to a specific outer class instance.
For example, AbstractMap
has a static inner class SimpleEntry
that represents a map entry. Since a map entry does not need access to the map that contains it, it can be static.
Inner classes are useful to keep the code that is tightly coupled together. Static inner classes have less overhead, since they dont retain the implicit "this" reference of the enclosing class (allowing any enclosing instance to be garbage collected independently).
Also, with static inner classes you can achieve complete encapsulation, even against classes in the same package. You can not make a normal class private, but you can have private inner classes. Try this convoluted example:
public class MyClass {
private static class MyInner {
private void myMethod() {
new Thread(new Runnable() {
public void run() {
while (true) {
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("Inner class still alive! "+this);
}
}
}).start();
}
}
public MyClass() {
new MyInner().myMethod();
}
protected void finalize() throws Throwable {
System.out.println("MyClass has just been finalized");
super.finalize();
}
public static void main(String[] args) {
new MyClass();
}
}
It demonstrates two things: The static inner class instance lives independently of the enclosing instance, and its completely encapsulated against outside access, even a class inheriting from MyClass can not access MyInner!
Note: The use of finalize() is discouraged, its only used here to demonstrate that the enclosing instance is really garbage collected.
It is useful if you want to create inner class without "wrapper" class instance. If inner class is not static, you cannot instantiate it without "wrapper" class instance.
I use it to have my database connection information, so I can load the configuration one time, and it is static, but it is only accessible by the parent class.
精彩评论