Is it possible in java to define an abstract method with wildcard but in the implementation use a concrete type
eg:
Define the abstract method in an abstract class like this
public abstract class AbstractAuthorizer {
abstract protected <T extends User> void authorize( T user );
}
Implement the abstract method like this, where CorporateUser extends User :
public class CorporateAuthorizer extends AbstractAuthorizer {
@Override
protected <CorporateUser> void authorize(CorporateUser user){
}
}
No you can't directly do what you're asking for. However, you can get the same effect.
When you make something generic, you're making a promise to the user: this will work for any type satisfying the generic bounds. So by picking a specific type in the subclass, you're breaking that rule. However, if you define the superclass correctly then you can get the behavior you want while satisfying the type checker as well. Instead of making the function generic, make the class generic, and then when you subclass it you get to choose which type it works on.
public abstract class AbstractAuthorizer<T extends User> {
abstract protected void authorize( T user );
}
public class CorporateAuthorizer extends AbstractAuthorizer<CorporateUser> {
@Override
protected void authorize(CorporateUser user) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With