【发布时间】:2016-12-09 09:40:08
【问题描述】:
我这里有一个简单的例子来说明我遇到的问题:
我有一个 Card 类,属性为“price”。
在这个 Card 类中,我有 2 个孩子,Copper 类和 Silver 类,每个孩子都有他们继承的价格和赢得的价值。
现在我制作了一个 ArrayList“手”,其中放了 2 张铜卡和 1 张银卡。直到这里OK。使用语句 System.out.println(hand.get(0));我得到“我是铜牌”,这没关系。使用 System.out.println(hand.get(0).getClass());我得到“铜类”,这也可以。但是,System.out.println(hand.get(0).getValue());不起作用,无法访问 Copper 的 getValue() 方法,只能访问 Card 类的 getPrice() 方法。
我在这里查看了类似的问题,但没有答案..谁能帮帮我!非常感谢!
PS这里是代码
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() 它返回 Copper 而不是 Card..
-
是的,因为这是获取您在运行时调用它的对象的类型。了解编译时类型和运行时类型之间的区别非常重要。
-
感谢乔恩,现在清楚了!我做了 Card 抽象并声明了抽象方法,它是这样工作的!我将对编译时和运行时类型做一些额外的阅读;-)
-
@JonSkeet 绝对正确!问题是当编译器“读取”它看到的代码时,您已经定义了一个
Card-objects 列表。在那一刻,它唯一能做的就是说:“好吧,这是Card对象的列表。可能是Coper对象,也可能是Silver对象或两者兼有。我不确定. 因为我只确定所有对象都是Card-objects,所以我只允许在Card类中定义的方法。”。 编译器不会运行您的代码:它不会创建对象并在其上调用方法!它只会读取和分析您的代码。它不知道getClass方法会返回什么。**
标签: java class inheritance