在父类中使用有关子类的方法是不好的做法?

时间:2017-11-10 19:25:57

标签: java oop

我会从一个例子开始,以更好地说明我所谈论的内容。

说我已经设置了以下类:

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)

所以我的问题是,这种做法有多糟糕?还有什么其他选择?

1 个答案:

答案 0 :(得分:4)

我认为更好的方法是让继承和多态为你做一些工作。请考虑以下事项:

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();
}