我在這裏有一個簡單的例子,只是爲了顯示我的問題: 我有一個卡類,與屬性「價格」。
這張卡片類我有2個孩子,銅類和銀類,每個類都有他們繼承的價格和他們的價值。 現在我製作一張ArrayList「手」,其中放置2張銅牌和1張銀牌。直到這裏OK。與聲明System.out.println(hand.get(0));我得到「我是銅牌」,這是可以的。使用System.out.println(hand.get(0).getClass());我得到「class copper」,這也是OK ..但是,System.out.println(hand.get(0).getValue()); dos不工作,來自Copper的getValue()方法無法訪問,只有Card類中的getPrice()方法.. 我在這裏查看類似的問題,但沒有答案的作品..誰可以幫助!非常感謝!
PS這裏是代碼在ArrayList中的子對象的屬性和方法不可見
public class Card {
int price;
public Card(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public String toString() {
return new String ("I am a card");
}
}
public class Copper extends Card {
int value;
public Copper(int price, int value) {
super(price);
this.value = value;
public int getValue() {
return value;
}
public int getPrice() {
return price;
}
public String toString() {
return new String ("I am a Copper card");
}
}
public class Silver extends Card{
int value;
public Silver(int price, int value) {
super(price);
this.value = value;
}
public int getValue() {
return value;
}
public int getPrice() {
return price;
}
public String toString() {
return new String ("I am a Silver card");
}
}
import java.util.ArrayList;
public class Start {
public static void main (String[] args)
{
Card Card1 = new Copper(0,1);
Card Card2 = new Copper(0,1);
Card Card3 = new Silver(3,2);
ArrayList<Card> hand = new ArrayList<Card>();
hand.add(Card1);
hand.add(Card2);
hand.add(Card3);
System.out.println(hand.get(0));
System.out.println(hand.get(0).getClass()); // --> OK
System.out.println(hand.get(0).getPrice()); // --> OK
System.out.println(hand.get(0).getValue()); // --> NOT OK
}
}
你的'Card'類沒有'getValue()'方法 - 你期望它調用什麼?這聽起來像'Card'應該是抽象的,並且聲明瞭一個抽象方法getValue()(或者把這個功能本身放在'Card'中)。 –
謝謝。然而,使用getClass()它會返回銅而不是卡.. – Bart
是的,因爲這是獲取您在運行時調用*的對象的類型*。瞭解編譯時類型和運行時類型之間的區別非常重要。 –