Enforcing return type for an class that implements an interface

后端 未结 7 1294
青春惊慌失措
青春惊慌失措 2021-01-11 11:51

How do I enforce that the method getFoo() in the implementing class, returns a list of the type of same implementing class.

public interface Bar{
     ....
          


        
7条回答
  •  死守一世寂寞
    2021-01-11 12:32

    This is not possible in Java, but you might wonder what the use-case is to force this in the interface.

    • If you program against the interface (which you typically do, why else define the interface) the type wouldn't be known
    • If you program against a specific class, this thread already provided options on how you can implement that specific class to return a List. And since you program against that specific class, the compiler has access to that specific return type and knows about it

提交回复
热议问题