Java中子类中的专门化方法参数 [英] Specializing method arguments in subclasses in Java

查看:356
本文介绍了Java中子类中的专门化方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下情况:

public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}

public abstract class Animal{

public void eat(AnimalFeed somethingToEat)

}

现在我想定义一个类Bird扩展动物肯定当鸟吃东西时,它只吃BirdFeed。

Now I would like to define a class "Bird" extending "Animal" being sure that when the bird eats, it eats only BirdFeed.

一种解决方案是指定一种合约,其中吃的来电者必须传递相应Feed的实例

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中子类中的专门化方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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