我将从一个示例开始,以更好地说明我在说什么。
假设我设置了以下课程:
public class Vegetable {
public String color;
public int weight;
public boolean isRedTomato() { // <- this is what concerns me
return this instanceof Tomato && color.equals("red");
}
public boolean isBigCucumber() { // <- this is what concerns me
return this instanceof Cucumber && weight >= 100;
}
}
public class Tomato extends Vegetable {
// some tomato specific methods and fields here
}
public class Cucumber extends Vegetable {
// some cucumber specific methods and fields here
}
我喜欢这样的事实是我可以做这样的事情:
public static void example(Vegetable[] box) {
for (Vegetable vegetable : box) {
if (vegetable.isBigCucumber()) { // <- I find this very handy
System.out.println("Found a big cucumber!");
}
if (vegetable.isRedTomato()) { // <- I find this very handy
System.out.println("Found a red tomato!");
}
}
}
一个人可能会同意
vegetable.isRedTomato()
看起来比类似的东西更自然
Tomato.isRedTomato(vegetable)
所以我的问题是,这种做法有多糟糕?还有哪些其他选择?
最佳答案
我认为一种更好的方法是让继承和多态为您完成一些工作。考虑以下:
public class Tomato extends Vegetable {
public void announce() {
if (color.equals("red")) {
System.out.println("Found a red tomato!");
}
else {
System.out.println("Found a tomato.");
}
}
}
public class Cucumber extends Vegetable {
public void announce() {
if (weight >= 100) {
System.out.println("Found a big cucumber!");
}
else {
System.out.println("Found a cucumber.");
}
}
}
现在,您不必在父类中进行任何类型检查。
for (Vegetable vegetable : box) {
vegetable.announce();
}
关于java - 在父类中具有涉及子类的方法是否是不好的做法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47229846/