Java Generics Generics

I have an interface:

public interface Human<D extends Details> {
    D getDetails();
}

      

And a specific impl:

public class Man implements Human<ManDetails> {
    ManDetails getDetails();
}

      

I would like to extend Man in such a way that I can do something like:

public class Baby extends Man {
    BabyDetails getDetails();
}

      

So, basically I'm looking for a way to make the person specific (I could use it on him), but also general so that others can extend it (for example, the getDetails () of the child will get a super .getDetails () and create a new one from it an instance of BabyDetails).

+3


source to share


1 answer


You can change your code to

class Man<T extends ManDetails> implements Human<T> {
    public T getDetails(){return null;}
}

      

which will allow you to do something like

class Baby extends Man<BabyDetails> {
    public BabyDetails getDetails(){...}
}

      

or

class Baby<T extends BabyDetails> extends Man<T> {
    public T getDetails(){...}
}

      



But as Sotirios Delimanolis already mentioned what you did is already great

public class Baby extends Man {
    public BabyDetails getDetails(){...}
}

      

because the overriding method can declare a new return type as long as that type is a subtype of the return type declared in the overridden method, for example

List<String> method()

      

can be overridden

ArrayList<String> method();

      

+1


source







All Articles