【发布时间】:2012-10-20 03:12:30
【问题描述】:
我怎样才能有一个类Fruit的多个扩展,并根据对象是什么类/类型,在这个水果上执行相同的方法但功能不同?
示例:我正在使用FruitManager 向水果店添加新的Fruit fruit = new Apple();。如果这个水果是苹果,我当然想把它添加到苹果列表中。香蕉清单也是如此。
现在,如果我有 10 种水果,我不想创建像 addBanana()、addApple() 等 10 个函数。
而且我也不想为了获得正确的水果清单而使用混乱的 if-else 语句。
我能否仅根据我添加的对象类型来获取水果列表?
class Fruit;
class Apple extends Fruit;
class Banana extends Fruit;
class FruitStore {
List<Fruit> apples = new ArrayList<Apple>();
List<Fruit> bananas = nwe ArrayList<Banana>();
}
class FruitManager {
FruitStore store;
//called from somewhere with Fruit fruit = new Apple();
addFruit(Fruit fruit) {
//how could things like this be done in one statement?
store.<get list apples or bananas>.add(fruit);
}
}
【问题讨论】:
-
您能解释一下将它们存储在单独列表中的必要性吗?
标签: java