问:
-----------------------------------------------------
我在J2SDK1。4。2的文档中看到这样的类
public abstract class MouseAdapter extends Object implements MouseListener
public abstract class WindowAdapter extends Object
implements WindowListener, WindowStateListener, WindowFocusListener
既然抽象类不能创建实例,那为什么new WindowAdapter(...){.....}
能被编译通过呢?
而且事件被执行得很好。
----------------------------------------------------
答:
----------------------------------------------------
Did you notice the difference between:
1, new WindowAdapter(..)
2, new WindowAdapter(..) {...}
The first tries to create an instance of WindowAdapter, we kmow it will fail, because WindowAdapter is an abstract class.
The second is doing a different thing. It creates a new anonymous class which extends WindowAdapter and the implementation is in the {...}
If you do not implement all abstract methods in the WindowAdapter, you still receive a compiler error.
Java supports anonymous class for programmers convenience. In this case, you do not have to write a small class in its own .java file and you do not care its name.
Anonymous class also support interfaces with the same syntax:
You have:
abstract class ClassA
interface InterfaceA
Then you can write code like:
new ClassA() { implementation }
new InterfaceA() { implementation }
In a compiler's eye, they are exactly the same as:
class Class$1 extends ClassA {implementation}
new Class$1(..)
class Class$2 implements InterfaceA {implementation}
new Class$2(..)
--------------------------------------------------