您的位置:首页 > 文档 > java >
 文章分类 

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


创建:2005-10-28 00:08:14
作者:Unlinux
来自: http://www.Unlinux.com

问:
-----------------------------------------------------

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

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

转载自:http://www.unlinux.com/doc/java/20051028/5500.html

评论】 【加入收藏夹】 【 】 【打印】 【关闭
 *  请尊重我们的劳动,转载请注明出自UnLinux.Com及作者名 * 

※ 相关链接
无相关信息
Copyright © 2005 UnLinux.Com All Rights Reserved