我们可以在 Java 中创建接口的实例吗?
是否可以在 Java 中创建接口的实例?
我在某处读到,使用内部匿名类我们可以这样做,如下所示:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
这里正确吗?
Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test {
public void wish();
}
class Main {
public static void main(String[] args) {
Test t = new Test() {
public void wish() {
System.out.println("output: hello how r u");
}
};
t.wish();
}
}
cmd> javac Main.java
cmd> java Main
output: hello how r u
Is it correct here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你永远无法在java中实例化接口。但是,您可以通过接口的类型来引用实现接口的对象。例如,
您上面所做的是创建一个实现该接口的匿名类。您正在创建一个匿名对象,而不是
接口测试
类型的对象。You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type
interface Test
.是的,你的例子是正确的。匿名类可以实现接口,这是我能想到的唯一一次您会看到一个类实现不带“implements”关键字的接口。在这里查看另一个代码示例:
这工作正常。取自此页面:
http://www.programmerinterview。 com/index.php/java-questions/anonymous-class-interface/
Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:
This works fine. Was taken from this page:
http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/
通常,您可以为接口创建引用。但你不能为接口创建实例。
Normaly, you can create a reference for an interface. But you cant create an instance for interface.
简短的回答...是的。初始化变量时可以使用匿名类。
看看这个问题:匿名内部类与命名内部类? - 最佳实践?
Short answer...yes. You can use an anonymous class when you initialize a variable.
Take a look at this question: Anonymous vs named inner classes? - best practices?
在我看来,不,您可以创建接口的引用变量,但不能像抽象类一样创建接口的实例。
No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.
是的,这是正确的。你可以用内部类来做到这一点。
Yes it is correct. you can do it with an inner class.
是的,我们可以,“匿名类使您能够使代码更加简洁。它们使您能够同时声明和实例化一个类。除了没有名称之外,它们就像本地类”->>Java 文档
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc