Java中没有接口的构造函数? [英] There is no constructor for interface in Java?
问题描述
在Java中,如果我有一个界面:
In Java, if I have an interface:
public interface MyInterface{
}
然后 MyInterface
实施是:
class MyClass implements MyInterface {
public MyClass(int a) {
}
}
所以我的意思是,如果用户想要声明一个 MyInterface
实例使用构造函数:
So what I mean is that if a user wants to do declare a MyInterface
instance with constructor:
MyInterface mine = new MyInterface(2);
然后就不可能了吗?
推荐答案
MyInterface mine = new MyInterface(2);
那么这是不可能的吗?
这是对的。你永远不能做类似的事情
That's right. You can never do something like
MyInterface mine = new MyInterface(2);
在新
之后你必须选择 class 实现接口(*),例如 MyClass
:
After new
you have to pick a class that implements the interface(*), such as MyClass
:
MyInterface mine = new MyClass(2);
为什么?
您可以想到接口作为类的属性。类比是形容词,例如红色。创建一个红球( new RedBall()
)或红色汽车( new RedCar()$ c>非常有意义$ c>),但只是创建红色(
new Red()
)没有意义(red what ??) 。
Why?
You can think of an interface as a property of a class. An analogy would be an adjective, such as "Red". It makes perfect sense to create, say, a red ball (new RedBall()
) or a red car (new RedCar()
), but just creating "red" (new Red()
) doesn't make sense ("red what??").
(*)您可以通过 new MyInterface(){...创建动态实现接口的匿名类。 }
但从技术上讲,你还在实例化一个类。
(*) You can create anonymous classes that implement the interface on the fly by doing new MyInterface() { ... }
but technically speaking you're still instantiating a class.
这篇关于Java中没有接口的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!