** 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.
我有三類:(父母)動物,(孩子)鳥和猴子
猴子有體重和兩只寵物,可以是另一只猴子或鳥
鳥有重量和名字(重量,名字)
它們一起形成了一個 TREE,其中葉節點是 Bird,非葉節點是 Monkeys(見圖片)
// 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;
}
}
uj5u.com熱心網友回復:
如果你想避免強制轉換,你可以在 Animal 型別上多型地實作搜索:
class Animal {
abstract Animal find(String name);
}
class Bird extends Animal {
String name;
@Override Animal find(String name) {
if (this.name.equals(name)) return this;
return null;
}
}
class Monkey extends Animal {
Animal left, right;
@Override Animal find(String name) {
Animal result = left.find(name);
if (result == null) result = right.find(name);
return result;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/378728.html
上一篇:子類的向量
下一篇:僅將唯一值推送到陣列(無重復值)
