您好,感谢您花时间查看我的问题。
我正在尝试对保存在对象数组中的对象调用方法。
共有三个类:Cards、Guard 和 Deck。
Guard 类扩展了 Cards 类。
该数组的类型为“Cards”,并在 Deck 类中实例化。
Cards 类几乎是空的:
public class Cards {
}
存储在数组中的对象是 Guard 类型。这是 Guard 类及其状态和方法:
public class Guard extends Cards{
private int cardScore = 2;
private String cardName = "Guard";
private String cardAbility = "this is the guard's ability";
public void printGuardInfo()
{
System.out.println("This card score fo the guard is: "+cardScore);
System.out.println("The card name is: "+ cardName);
System.out.println("The card ability is" + cardAbility);
}
}
我正在 Deck 类中实例化数组。然后我用 Guard 类型的对象填充类型 Cards 的数组。我相信这就是多态性。
这行得通,我可以打印在每个索引点保存的引用变量。
public class Deck {
Cards[] deck = new Cards[16];
public Cards[] getDeck() {
return deck;
}
public void addGuards()
{
for(int i=0; i<5; i++)
{
deck[i] = new Guard();
deck[i].printGuardInfo();// Error: cannot resolve method printGuardInfo()
}
}
}
我的问题是我现在无法调用 deck[i] 上的 printGuardInfo() 方法。
我已经搜索并用谷歌搜索了一段时间,但没有成功。我觉得我需要一个接口(interface),或者某种抽象类。不幸的是,我在这些领域的知识还不够。
非常感谢任何帮助,谢谢。
最佳答案
我会推广这样的东西:
使Cards
成为接口(interface)
public interface Cards {
void print();
}
让 Guard
实现这个接口(interface),并用所需的信息重写 print
方法。
public class Guard implements Cards{
// ... Other methods and stuff
@Override
public void print() {
System.out.println("This card score fo the guard is: "+cardScore);
System.out.println("The card name is: "+ cardName);
System.out.println("The card ability is" + cardAbility);
}
// ... Other methods and stuff
}
现在在循环中你只需要调用
deck[i].print();
现在要打印什么将取决于必须打印什么的实际实现,但一般来说 Cards
类将知道它现在可以打印
。
编辑:在@chrylis 评论之后,您的类应该被称为Card
而不是Cards
。原因在这里?它就像是针对单一类型 Card
(此处为类)的简单计划,但不代表多个 Cards
(多个卡片将是 Card 的实例
)。
关于java - 如何在 Java 中调用存储在多态数组中的对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378915/