我这里有一个简单的例子来说明我遇到的问题:
我有一个 Card 类,其属性为“价格”。
在这个 Card 类中,我有 2 个子类,Copper 类和 Silver 类,每个类都有它们继承的价格和赢得的值(value)。
现在我制作了一个 ArrayList“手”,其中放置了 2 张铜卡和 1 张银卡。到这里就OK了。使用语句 System.out.println(hand.get(0));我得到“我是一张铜卡”,这没关系。使用 System.out.println(hand.get(0).getClass());我得到“class Copper”,这也可以..但是,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
}
}
最佳答案
System.out.println(hand.get(0).getValue()); // --> NOT OK
因为您声明了列表:ArrayList<Card> hand
,所以所有元素都是 Card
输入,但是您没有 getValue()
方法在你的 Card
类。
您可以创建 getValue()
在您的父类(super class)( Card
)中,并让子类覆盖它,如果您的子类需要使用此方法做一些特殊的事情。
关于java - ArrayList 中子对象的属性和方法不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057296/