【发布时间】:2022-01-14 19:13:14
【问题描述】:
** UPDATE: Solved! **
I created abstract parent class with 2 methods, getWeight() and getName()
In Bird class, getName() will return the bird's name.
In Monkey class, getName() will call it's pets and return the result from whichever pet returns the name.
Then I just call getName() in root monkey class and let it find the name for me.
我有三个班级:(父母)动物,(孩子)鸟和猴子
猴子有体重和两只宠物,可以是另一只猴子或鸟
鸟有体重和名字(体重,名字)
它们一起形成一棵树,其中叶节点是鸟,非叶节点是猴子 (见视觉)
// Monkey, weight=40
// / \
// / \
// / \
// Bird(5,"Big Bird") Monkey,weight=25
// / \
// / \
// / \
// / \
// Bird(weight=7, name="BirdMan") Bird(w=11, n="Stinky")
在递归遍历这棵树以查找具有特定名称的鸟时,我需要检查当前节点是鸟还是猴子
// psuedo-is code
String recursive(Animal root, String target){
if (root instanceof Bird && root.name == target) return root.name;
// else, its not a Bird, its a Monkey
else
Animal left = root.left;
Animal right = root.right;
if (recursive(left) == target) return target;
if (recursive(right) == target) return target;
return "not found";
}
当我尝试这样做时,它会说
error: cannot find symbol [in Main.java]
Animal left = root.left;
我想在这个问题中使用父子继承,但它不允许我访问子对象的属性,因为我在变量中使用父对象声明。
我该如何解决这个问题?我想使用继承,但我无法弄清楚。 请帮忙。 我在下面的代码中还有一些小问题。如果有人可以帮助澄清这些,那将非常有帮助。
// animal parent class
class Animal {
int weight;
public Animal (int weight) {
this.weight = weight;
}
}
// child class Bird, has weight & name
class Bird extends Animal{
int name;
public Bird (int weight, String name) {
// * Question 1*
// btw, is this line super(w) necessary?
//is it because the constructor of bird & animal have different args?
// do i have to say this.weight = weight;? or is that implied from super(w)? whats the most efficient way of declaring the inheritance i'm trying to establish?
super(w);
this.weight = weight;
this.name = name;
}
}
// child class Monkey, has weight & two pets (can be Monkey, or Bird)
class Monkey extends Animal{
// *Question 2* Since animal can be both Monkey or Bird, I used parent class to do this.
// is there a better way to do this?
// I tried
Animal left;
Animal right;
public Monnkey(int weight, Animal left, Animal right) {
super(w);
this.weight = weight;
this.left = left;
this.right = right;
}
}
【问题讨论】:
-
你是在问怎么投吗?
-
我尝试了投射,并且成功了。但有人告诉我选角不是一个好习惯。有没有其他方法可以实现这种父子关系?
-
真的需要类层次结构吗?也许
Animal是唯一需要的类,它提供了AnimalType属性。这消除了对子类的需要。另一种选择是将Animal抽象化,以便所有子类都必须实现AniamlType getType()方法。无论哪种方式都消除了投射的需要。一般来说,更喜欢组合而不是继承(假设您有设计控制权)。
标签: java oop inheritance polymorphism