In Java, if I have an interface:
public interface MyInterface{
}
Then MyInterface implementation is:
class MyClass implements MyInterface {
public MyClass(int a) {
}
}
So what I mean is that if a user wants to do declare a MyInterface instance with constructor:
MyInterface mine = new MyInterface(2);
then it is not possible right?
解决方案
MyInterface mine = new MyInterface(2);
then it is not possible right?
That's right. You can never do something like
MyInterface mine = new MyInterface(2);
After new you have to pick a class that implements the interface(*), such as MyClass:
MyInterface mine = new MyClass(2);
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??").
(*) 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.