【发布时间】:2020-03-28 12:59:09
【问题描述】:
HandDrawn class extends the super-class Car, as you can see. The problem is it doesn't print out the the String name when i try to print the ArrayList that stores the objects. Btw, the ArrayList stores objects of the class Car.
冷静点,如果我对这个问题做了一些冒犯了你的小感受的事情,请不要投反对票...告诉我发生了什么,以便我知道未来。
public class HandDrawn extends Card {
private boolean niceDrawing;
public HandDrawn(String name, boolean niceDrawing) {
super(name);
this.niceDrawing = niceDrawing;
}
@Override
public String toString() {
return "HandDrawn{" +
"niceDrawing=" + niceDrawing +
'}';
}
public void setNiceDrawing() {
this.niceDrawing = niceDrawing;
}
public boolean getNiceDrawing(boolean niceDrawing) {
return this.niceDrawing;
}
}
public class Main {
static ArrayList<Card> cards = new ArrayList<>();
public static void main(String[] args) {
cards.add(new HandDrawn("Anna", true));
cards.add(new HandDrawn("Kalle", false));
Main myApp = new Main();
myApp.cardList(cards);
}
public void cardList(ArrayList<Card> e) {
for (int i = 0; i <e.size(); i++) {
System.out.println(e.get(i));
}
}
}
这是Main类和HandDrawn类
【问题讨论】:
-
如果您将 Car 超类和使用 ArrayList 的特定案例的示例包含在内,这个问题会更清楚,但它似乎无法按您的预期工作。
-
@DatuPuti Ye 已修复
-
一目了然,我认为这不会像您在此处列出的那样编译,但我可能是错的……使用当前格式(或缺少格式)很难阅读。也许问题是在调用 cardList 之前您从未调用静态方法“main”——ArrayList 中没有任何内容,因为您尚未执行以“cards.add...”开头的行。
-
可以编译,可能是因为 HandDrawn 类里面的 toString 里面没有实例变量名?
-
不,它在类定义中,所以你不需要使用“this”关键字来明确...对不起,我已经很久没有使用Java了——我现在回答你的问题。
标签: class object inheritance arraylist