How do you create a subclass so that the parameters are of the subclass type in Java

寵の児 提交于 2019-12-21 20:27:34

问题


I have the abstract parent class Animal:

public abstract class Animal
{
    public abstract <T extends Animal> T copyAnimal(T animal);
}

I then want to create a subclass Duck but to override the copyAnimal I want to use Duck as the parameters such that:

public class Duck extends Animal
{
    @Override
    public Duck copyAnimal(Duck duck)
    {
        return copyOfDuck;
    }
}

This of course gives me a compiler error saying that the method is not overridden. That being said how can I adjust this code so that I don't have to pass Animal to the copyAnimal() method to save casting, etc. since it looks ugly and would require additional runtime checks. Or is it even possible? And if not then what's the most elegant solution?


回答1:


public abstract class Animal<A extends Animal<A>>
{
    public abstract A copyAnimal(A animal);
}

Then:

public class Duck extends Animal<Duck>

Note that you can't constrain it to be the "self" type (e.g. it could be Duck extends Animal<Pig>); you just have to only declare the classes you want to declare.



来源:https://stackoverflow.com/questions/49457487/how-do-you-create-a-subclass-so-that-the-parameters-are-of-the-subclass-type-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!