How to create subclasses so that parameters belong to subclass types in Java

I have an abstract parent class animal:

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

Then I want to create a subclass duck, but to override copyanimal, I want to use duck as a parameter, as follows:

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

This of course gave me a compiler error, indicating that the method was not overridden That is, how can I adjust this code so that I don't have to pass animal to the copyanimal () method to save the transformation and so on, because it looks ugly and requires additional runtime checks Or even possible? If not, what is the most elegant solution?

Solution

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

then:

public class Duck extends Animal<Duck>

Note that you cannot limit it to the "self" type (for example, it may be duck extensions animal < pig >); You only need to declare the class you want to declare

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>