能够实例化接口 [英] Ability to instantiate an interface

查看:173
本文介绍了能够实例化接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是可以实例化一个界面:

I have the impression that it is possible to instantiate an interface:

interface TestA { 
   String toString(); 
}

public class Test {
    public static void main(String[] args) {

       System.out.println(new TestA() {
          public String toString() { 
              return "test"; 
          }
       });
    }
 }

打印test 。为什么?该类没有实现接口。

This prints "test". Why? The class doesn't implement the interface.

它还使用 new TestA()创建它的实例但是我读取的接口无法实例化。

Also it creates an instance of it using new TestA() but I read interfaces cannot be instantiated.

有人可以解释为什么打印成功吗?

Can someone please explain why it prints successfully ?

推荐答案

什么正在进行



你在这里做的是创建一个匿名类,并实例化它。所以你的对象的类型不是 TestA ,但实际上是匿名类的类型。

What is going on

What you are doing here is creating an anonymous class, and instantiating it. So your object's type is not TestA, but actually the type of the anonymous class.

TestA myObject = new TestA(){ ... }

是一个快捷方式:

class ClassA implements TestA { ... }
TestA myObject = new ClassA();

在此示例中,尽管引用 myObject的类型为 TestA ,引用的对象的类型是 ClassA ,它实现 TestA

In this example, although the type of the reference myObject is TestA, the type of the referenced object is ClassA, which implements TestA.

您可以在Java教程中阅读有关匿名类的信息在其中

You can read about anonymous classes in the Java Tutorial here.

正在发生的事情的最后一步是你的 System.out.println 在创建的对象上,因此调用其 toString()方法。

The last step of "what is going on", is your call of System.out.println on the created object, which as a consequence calls its toString() method.

因此,为了打破发生的所有步骤,您的代码相当于:

So to break up all the steps that are happening, your code is equivalent to :

public class Test {

   public static void main(String[] args){

      class ClassA implements TestA {

        public String toString(){
            return "test";
        }
      }
      TestA myObject = new ClassA();
      String myString = myObject.toString();
      System.out.println(myString);
   }
}



回答你的确切问题



所以回答你的确切问题:

Answer to your precise questions

So to answer your precise questions :


  • 的确,你的班级测试没有实现接口,匿名类就是这样。这样做是因为它被声明为实现它,并且因为它正确地实现了抽象方法 toString

  • 的确,接口无法实例化。在这种情况下,您不是实例化接口,而是您定义为实现接口的匿名类。

  • indeed, your class Test doesn't implement the interface, the anonymous class does. It does both because it is declared as implementing it, and because it correctly implements the abstract method toString
  • indeed, interfaces cannot be instantiated. In this case, you are not instantiating the interface, but the anonymous class that you define as implementing the interface.

如果您愿意要检查第二点,您可以尝试删除匿名类定义的主体。它不会编译:

If you would like to check that second point, you can try removing the body of your anonymous class definition. It won't compile :

System.out.println(new TestA()); // Compile error

这篇关于能够实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆