Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Of Generics

Tags:

java

generics

I have an interface:

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

And a concrete impl:

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

I'd like to extend Man in such a way so I could do something like:

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

So basically I'm looking for a way so Man would be concrete (I would be able to use it on it's own) but also a generic so others can extends it (for example, getDetails() of baby will get super.getDetails() and create a new instance of BabyDetails from it).

like image 957
shayy Avatar asked Dec 04 '25 02:12

shayy


1 Answers

You may consider changing your code to

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

which would let you 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 fine

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

because overriding method can declare new return type as long as this type is subtype of return type declared in overridden method, for instance

List<String> method()

can be overridden by

ArrayList<String> method();
like image 55
Pshemo Avatar answered Dec 06 '25 17:12

Pshemo



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!