【问题标题】:How is the interface being instantiated, without implementation of any class? [duplicate]没有实现任何类,接口是如何被实例化的? [复制]
【发布时间】:2020-11-07 20:58:51
【问题描述】:
public interface InterfaceTest {
    interface Gift  { void present(); }
    interface Guest { void present(); }
    interface Presentable extends Gift, Guest { }
    public static void main(String[] args) {
        Presentable johnny = new Presentable() {
                @Override public void present() {
                    System.out.println("Heeeereee's Johnny!!!");
                }
            };
        johnny.present();                     
        ((Gift) johnny).present();            
        ((Guest) johnny).present();           
        Gift johnnyAsGift = (Gift) johnny;
        johnnyAsGift.present();              
        Guest johnnyAsGuest = (Guest) johnny;
        johnnyAsGuest.present();
    }
}

此代码编译并运行 main() 函数没有错误,我这里缺少什么概念?

【问题讨论】:

    标签: java interface instantiation bluej


    【解决方案1】:

    johnnyanonymous subclass 的一个实例。从链接:

    匿名类使您的代码更简洁。他们 使您能够同时声明和实例化一个类。他们 类似于本地类,只是它们没有名称。使用它们 如果您只需要使用一次本地类。

    您的代码编译的原因是present 的实现是在这个匿名子类中提供的。为了进一步推动这一点,这是:

    Presentable johnny = new Presentable();
    

    无法编译。但是,这个:

    Presentable johnny = new Presentable() {
        @Override public void present() {
             // Do something
        }
    };
    

    完全有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2018-01-20
      相关资源
      最近更新 更多