Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract generic method with wild card implemented with concrete type

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){
    }
}
like image 775
user1730326 Avatar asked Jan 03 '23 17:01

user1730326


1 Answers

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) {}
}
like image 200
Silvio Mayolo Avatar answered Jan 13 '23 17:01

Silvio Mayolo