Enforcing return type for an class that implements an interface

后端 未结 7 1222
青春惊慌失措
青春惊慌失措 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:47

    The interface Bar> answers already here are right, but I just wanted to add that if this is really something you want to enforce, you may want to look at composing your objects rather than using inheritance. Without knowing too much about your classes, it might look something like this:

    public interface FooGetter {
        List getFoo();
    }
    
    public class FooComposer {
        ...
        final T bar;
        final FooGetter barGetter;
    }
    

    Or it could look very different... but the main point is that if you want the two Ts to match, composition may be the answer.

    Of course, even that can be circumvented using raw types... but then again, if someone does that, they're just using a raw List, and when they get ClassCastExceptions you can safely hit them. :)

提交回复
热议问题