【发布时间】:2013-12-17 15:54:45
【问题描述】:
我遇到过这样的课程。它拥有一个“with”方法,可以让人们将事物链接在一起。
public class Bear {
protected List<String> names = new ArrayList<String>();
protected List<String> foods = new ArrayList<String>();
public Bear withName(String name) {
names.add(name);
return this;
}
public Bear withFood(String food) {
foods.add(food);
return this;
}
}
// ...somewhere else
Bear b = new Bear().withName("jake").withName("fish");
我发现两个类共享 90% 的相同代码。因此,我在它们之间创建了一个基类,并将 25 个左右的“with”方法转移给它(包括成员变量和所有)。就像这样:
public abstract class Animal {
protected List<String> names = new ArrayList<String>();
public Animal withName(String name) {
names.add(name);
return this;
}
}
public class Bear extends Animal {
protected List<String> foods = new ArrayList<String>();
public Bear withFood(String food) {
foods.add(food);
return this;
}
}
但是,这现在破坏了一切(并且有很多地方在这两个类的设计中使用它)。
Bear b = new Bear().withName("jake"); // Breaks
bear b2 = new Bear().withFood("fish"); // Fine
给出的错误:
类型不匹配:无法从 Animal 转换为 Bear
显然,当您返回基类 this 时,它返回的是 Bear 类型,并且不会进行任何类型的自动转换。
我有哪些选择来解决/绕过这个问题?
【问题讨论】:
-
可以,我不清楚哪种方法有效,哪种方法无效。
标签: java types polymorphism