简体   繁体   English

我们可以为接口和抽象类创建 object 吗?

[英]Can we create object to interfaces and abstract classes?

f.addMouseMotionListener(new MouseAdapter() {
    public void mouseDragged(MouseEvent e) 
    {
        String s="Mouse dragging :X = "+e.getX()+" Y= "+e.getY();
        tf.setText(s);
    }
    });

i read that we cannot instantiate objects for Abstract classes...but here we are creating new MouseAdapter() ..can someone explain how is it done with these anonymous classes..thank u.我读到我们不能为抽象类实例化对象……但是在这里我们正在创建new MouseAdapter() ..有人可以解释一下这些匿名类是如何完成的……谢谢。

You're not creating an instance of MouseAdapter , you are creating an instance of an anonymous class inheriting from MouseAdapter .您不是在创建MouseAdapter的实例,而是在创建一个继承自MouseAdapter的匿名 class 的实例。

More verbosely, this could have been written:更详细地说,这可以写成:

class Goo extends MouseAdapter { public void mouseDragged(){...} };

f.addMouseMotionListener(new Goo());

You don't see it doesn't mean it won't happen.你没有看到它并不意味着它不会发生。 Just from the code, you use new MouseAdapter() to construct an object.仅从代码中,您就可以使用 new MouseAdapter() 构造一个 object。 However, if you try to read the content in.class file, you will find that the inner class has name, the usual case is,但是,如果你尝试读取.class文件中的内容,你会发现里面的class有名字,通常的情况是,

class MouseAdapter$1 extends MouseAdapter

Till this, you should clear about everything.到此为止,您应该清楚一切。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM