Constructor in an Interface?

前端 未结 11 1072
鱼传尺愫
鱼传尺愫 2020-12-02 06:38

I know it\'s not possible to define a constructor in an interface. But I\'m wondering why, because I think it could be very useful.

So you could be sure that some fi

11条回答
  •  执念已碎
    2020-12-02 07:14

    A work around you can try is defining a getInstance() method in your interface so the implementer is aware of what parameters need to be handled. It isn't as solid as an abstract class, but it allows more flexibility as being an interface.

    However this workaround does require you to use the getInstance() to instantiate all objects of this interface.

    E.g.

    public interface Module {
        Module getInstance(Receiver receiver);
    }
    

提交回复
热议问题