Enforcing return type for an class that implements an interface

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

    Unfortunately this cannot be enforced by Java's type system.

    You can get pretty close, though, by using:

    public interface Bar> {
        List getFoo();
    }
    

    And then your implementing classes can implement it like so:

    public class SomeSpecificBar implements Bar {
        // Compiler will enforce the type here
        @Override
        public List getFoo() {
            // ...
        }
    }
    

    But nothing stops another class from doing this:

    public class EvilBar implements Bar {
        // The compiler's perfectly OK with this
        @Override
        public List getFoo() {
            // ...
        }
    }
    

提交回复
热议问题