我确信这在以 Java 为中心的 OOP 中非常普遍。在java中有没有办法制作一个接受所有继承子类型的基类型变量?就像我有;
class Mammal {...}
class Dog extends Mammal {...}
class Cat extends Mammal {...}
class ABC {
private Mammal x;
ABC() {
this.x = new Dog();
-or-
this.x = new Cat();
}
}
我也需要该变量能够接受任何扩展版本,但不是特定的一种扩展类型。
有一些方法我知道,但不想使用。我可以为每个子类型创建一个属性,然后只使用一个属性。制作一个阵列并将其推入其中。
获得“基类”类型变量的任何其他想法或方法?
好的,因为我知道在 Java 中使用多态鸭子类型并不是一个好主意,但是因为我认为我无法避免它。是动态使用子类方法重新分配变量的强制转换版本的唯一方法,即,我得到一个错误;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
x.bark();
} else if (x instanceof Cat) {
x.meow();
}
说未找到符号,但这有效;
Mammal x;
x = new Dog();
System.out.println(x.getClass());
x.breath();
if (x instanceof Dog) {
Dog d = (Dog) x;
d.bark();
} else if (x instanceof Cat) {
Cat c = (Cat) x;
c.meow();
}
最后一个是唯一的方法吗?