There is no constructor for interface in Java?

前端 未结 6 571
深忆病人
深忆病人 2020-12-17 06:48

In Java, if I have an interface:

public interface MyInterface{
}

Then MyInterface implementation is:

class MyC         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-17 07:06

    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.

提交回复
热议问题