java 参数子类,Java中子类中的专门化方法参数

Consider the following situation:

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 {

public abstract void eat(F somethingToEat);

}

Then you can declare your subclasses as wanting a particular type of AnimalFeed:

public class Bird extends Animal {

public void eat(BirdFeed somethingToEat) {}

}

public class Fish extends Animal {

public void eat(FishFeed somethingToEat) {}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值