abstract类是不能创建实例的,可为什么会出现。。。。?

王朝other·作者佚名  2008-05-18
窄屏简体版  字體: |||超大  

问:

-----------------------------------------------------

我在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(..)

--------------------------------------------------

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航