我可以为接口创建对象吗? [英] Can I create an object for Interface?
问题描述
是否可以为接口创建对象?如果是,该怎么做?
根据我的观点,以下代码表明我们可以:
Is it possible to create an object for an interface? If yes, how is it done? According to my view the following code says that we can:
Runnable r = new Runnable() {
// some implementation
}
推荐答案
这不是创建Interface的实例,而是创建实现接口的类。因此,当您编写以下内容时:
This is not creating the instance of Interface, it is creating a class that implements interface. So when you write:
Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
};
您实际上是在创建一个实现Runnable接口的类。
您需要在这里遵循所有规则,在这里,我们将覆盖 Runnable
的run方法。抽象类也有类似的东西。我们可以使用一个示例进行测试:
You are actually a creating a class that is implementing the Runnable interface.
You need to follow all rules here, here, we are overriding the run method for Runnable
. There is similar thing for abstract class also. We can test using an example:
public abstract class AbstractClass {
public void someMethod() {
System.out.println("abstract class");
}
}
和另一个类,即 TestClass
:
public class TestClass {
public static void main(String[] args) {
AbstractClass abstractClass = new AbstractClass() {
public void someMethod() {
System.out.println("concrete class method");
}
};
abstractClass.someMethod();
}
}
这将创建一个我们覆盖其中的子类的实例 someMethod()
;
该程序打印:
This will create the instance of a subclass in which we are overriding someMethod()
;
This program prints:
concrete class method
这证明我们正在创建子类的实例。
This proves we are creating the instance of subclass.
这篇关于我可以为接口创建对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!