【发布时间】:2021-03-06 19:52:49
【问题描述】:
我们可以在两种实现中对 cat 和 dog 对象使用同名的 getWeight() 方法。我找不到两个实现之间的任何区别。在这里使用多态或覆盖有什么好处吗?
首次实施
public class Cat{
public int getWeight() { return 5; }
}
public class Dog {
public int getWeight() { return 7; }
}
public class Main {
public static void main(String [] args) {
Dog dog = new Dog();
Cat cat = new Cat();
System.out.println(dog.getWeight());
System.out.println(cat.getWeight());
}
}
第二次实施
public class Cat extends Animal{
public int getWeight() { return 5; }
}
public class Dog extends Animal{
public int getWeight() { return 7; }
}
public class Animal {
public int getWeight() return 10;
}
public class Main {
public static void main(String [] args) {
Animal dog = new Dog();
Animal cat = new Cat();
System.out.println(dog.getWeight());
System.out.println(cat.getWeight());
}
}
【问题讨论】:
-
我只会在 Animal 中有一个 setWeight() 类和实例变量,而在子类中没有它。
-
投票关闭“需要更多关注”。以一种或另一种方式做这件事可能有好处,但我们不能从你的简短讨论中说出来。一般来说,没有偏好。
-
这取决于
Cat和Dog实例需要做什么。例如,尝试使用每个实现创建一个包含Cats 和Dogs 的列表。 -
标记问题:OP 需要解释代码的用途。需要更多关于正在构建的内容的背景才能给出答案。
标签: java oop polymorphism