Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encountering type safety warning when using Generics

I have a class that looks like this.

class SuperClass<T> {
    public <K extends ClassB> K someMethod(T t) {
        return null;
    }
}

class ClassB {

}

class ClassA extends ClassB {

}

class ClassC {

}


public class Main extends SuperClass<ClassC>{
    @Override
    public ClassA someMethod(ClassC c) { //type safety warning in ClassA
        return null;
    }
}

From my understanding, the return type of someMethod() can be any class that extends ClassB or ClassB itself. Clearly ClassA is ClassB. What seems to be the problem and why am I getting a type safety warning?

like image 461
EDR Avatar asked May 18 '26 21:05

EDR


1 Answers

public <K extends ClassB> K someMethod(T t) {
    return null;
}

You're making a guarantee to the callers here. You're telling them "no matter what subclass of SuperClass we're working with, this method will return a value that can safely be treated as any subclass of ClassB". Then your subclass Main comes along and breaks that promise, by making a version that only returns ClassA, which is a direct violation of the contract you've made. The generic extends / super declarations are promises to the caller, not to the person extending the code.

like image 65
Silvio Mayolo Avatar answered May 21 '26 12:05

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!