简体   繁体   English

实例化匿名类时可以实现接口吗?

[英]Can I implement an interface while instantiating an anonymous class?

Suppose I have an abstract class FactorizedDialog . 假设我有一个抽象类FactorizedDialog It looks like this (please note that this is just some dummy example) 看起来像这样(请注意,这只是一些虚拟示例)

public abstract class FactorizedDialog extends Dialog {

  public abstract void myMethod();
} 

Now I can do something like this: 现在我可以做这样的事情:

FactorizedDialog dialog = new FactorizedDialog() {

            @Override
            public void myMethod() {
                // implementation here
            }
}

As you may have guessed I extend Dialog (which is in fact an abstract class) only to add a method to it so I can override it when I create an anonymous class. 正如您可能已经猜到的那样,我扩展Dialog(实际上是抽象类)只是为了向其添加方法,以便在创建匿名类时可以覆盖它。 Is it possible to implement an interface in java while I instantiate Dialog instead of using my derived abstract class? 在实例化Dialog而不是使用派生的抽象类时,是否可以在Java中实现接口?

No, when you specify the superclass of an anonymous inner class you can either specify a normal class to extend or an interface, but not both. 不,当你指定一个匿名内部类的父类,你可以指定一个普通的类来扩展接口,但不能同时使用。 The syntax shown in section 15.9 of the JLS simply doesn't allow for both. JLS第15.9节中显示的语法根本不允许两者。

If you mean the below where Dialog is an interface, then yes it can be done. 如果您在下面是Dialog是接口的意思,那么可以的。

Dialog dialog = new Dialog() {

    @Override
    public void myMethod() {
    }
}

Of course then the declaration of myMethod should go into the Dialog interface. 当然, myMethod的声明应该进入Dialog接口。

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

相关问题 扩展接口与通过匿名类实例化 - Extending an Interface vs Instantiating via Anonymous Class 实例化接口时如何实现自己的方法? - How can I implement my own method when instantiating an interface? 扩展类(例如枚举)的匿名.class能否以实现接口的方式被黑客入侵? - Can an anonymous .class that extends a class (such as an enum) be hacked in such a way as to implement an interface? object 的类型,同时实例化实现接口的 class - Type of object while instantiating a class that implements interface 实例化抽象类时发生了什么? 什么是匿名内部课程? - What is happening while instantiating an abstract class? What is an anonymous inner class? java在匿名类中实现泛型接口 - java implement generic interface in an anonymous class 在C ++中使用匿名类实现接口 - Implement Interface with Anonymous Class in C++ 在Jython中,我可以创建一个实现Java接口的内联匿名类吗? - In Jython, can I make an inline anonymous class that implements a Java interface? 何时在类中实现接口以及何时实例化接口的匿名实现 - When to implement interface in class and when to instantiate an anonymous implementation of an interface 循环继承和接口——A类不能实现B类接口而B类实现A接口 - Cyclic inheritance and interfaces - class A can't implement class B interface while class B implements A interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM