如何创建子类,以便参数属于Java中的子类类型 [英] How do you create a subclass so that the parameters are of the subclass type in Java

查看:123
本文介绍了如何创建子类,以便参数属于Java中的子类类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有抽象的父类Animal:

I have the abstract parent class Animal:

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

然后我要创建一个子类Duck但是要覆盖我想要的copyAnimal使用Duck作为参数:

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;
    }
}

这当然给了我一个编译错误,说明了方法未被覆盖。这就是说我怎么能调整这个代码,这样我就不必将Animal传递给copyAnimal()方法来保存转换等等,因为它看起来很丑,需要额外的运行时检查。或者甚至可能吗?如果没有,那么最优雅的解决方案是什么?

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?

推荐答案

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

然后:

public class Duck extends Animal<Duck>

请注意,您不能将其约束为自我类型(例如,它可能是 Duck extends Animal< Pig> );你只需要声明你想要声明的类。

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.

这篇关于如何创建子类,以便参数属于Java中的子类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆