Specializing method arguments in subclasses in Java(在 Java 的子类中专门化方法参数)
问题描述
考虑以下情况:
public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}
public abstract class Animal{
public void eat(AnimalFeed somethingToEat)
}
现在我想定义一个扩展动物"的鸟"类,确保当鸟吃东西时,它只吃鸟食.
Now I would like to define a class "Bird" extending "Animal" being sure that when the bird eats, it eats only BirdFeed.
一种解决方案是指定一种合约,其中吃"的调用者必须传递适当提要的实例
One solution would be to specify a sort of contract, in which the caller of "eat" must pass an instance of the appropriate feed
public class Bird extends Animal{
@Override
public void eat(AnimalFeed somethingToEat){
BirdFeed somethingGoodForABird
if(somethingToEat.instanceOf(BirdFeed)){
somethingGoodForABird = (BirdFeed) somethingGoodForABird
}else{
//throws error, complaining the caller didn't feed the bird properly
}
}
}
将参数的责任委托给调用者是否可以接受?如何强制调用者传递参数的特化?是否有替代设计解决方案?
Is it acceptable to delegate the responsibility of the parameter to the caller? How to force the caller to pass a specialization of the parameter? Are there alternative design solutions?
推荐答案
你需要在类中添加一个类型变量:
You'd need to add a type variable to the class:
public abstract class Animal<F extends AnimalFeed> {
public abstract void eat(F somethingToEat);
}
然后您可以将您的子类声明为需要特定类型的 AnimalFeed
:
Then you can declare your subclasses as wanting a particular type of AnimalFeed
:
public class Bird extends Animal<BirdFeed> {
public void eat(BirdFeed somethingToEat) {}
}
public class Fish extends Animal<FishFeed> {
public void eat(FishFeed somethingToEat) {}
}
这篇关于在 Java 的子类中专门化方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 的子类中专门化方法参数


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01