Java – enforces return types for classes that implement interfaces

How to enforce the getfoo () method in an implementation class to return a list of types of the same implementation class

public interface Bar{
     ....
     List<? extends Bar> getFoo(); 
}

Now, the class that implements bar returns the object of any class that implements bar I want to make it more strict, so the class that implements bar returns a list of objects of type only in getfoo ()

Solution

Unfortunately, this cannot be enforced by the Java type system

However, you can use the following methods,

public interface Bar<T extends Bar<T>> {
    List<T> getFoo();
}

Then your implementation class can be implemented as follows:

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

But nothing can stop another course

public class EvilBar implements Bar<SomeSpecificBar> {
    // The compiler's perfectly OK with this
    @Override
    public List<SomeSpecificBar> getFoo() {
        // ...
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>