[英]How can I call a method on an object that is stored in a polymorphic array in Java?
Hi and thanks for taking time to look at my problem. 您好,感谢您抽出宝贵时间来查看我的问题。
I am trying to call a method on an object held in an object array. 我试图在对象数组中保存的对象上调用方法。
There are three classes: Cards, Guard and Deck. 共有三类:纸牌,守卫和甲板。
The Guard class extends the Cards class. Guard类扩展了Cards类。
The array is of type 'Cards' and is instantiated in the Deck class. 该数组的类型为Cards,并在Deck类中实例化。
The Cards class is pretty much empty: Cards类几乎是空的:
public class Cards {
}
The object being stored in the array is of type Guard. 存储在数组中的对象的类型为Guard。 Here is the Guard class and it's state and methods: 这是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);
}
}
I am instantiating the array in the Deck class. 我正在Deck类中实例化数组。 I am then filling a array of type Cards with objects of type Guard.This is polymorphism, I believe. 然后我用Guard类型的对象填充Card类型的数组。我相信这是多态的。
This works and I can print the reference variables held at each index point. 这行得通,我可以打印每个索引点上保存的参考变量。
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()
}
}
}
My problem is that I now cannot call the printGuardInfo() method on deck[i]. 我的问题是我现在无法在deck [i]上调用printGuardInfo()方法。
I have searched and googled for a while now but with no success. 我已经搜索和搜索了一段时间,但没有成功。 I feel like I need an interface, or abstract class of some sort. 我觉得我需要一个接口或某种抽象类。 Unfortunately I am not knowledgeable enough in these areas. 不幸的是,我在这些领域知识不足。
Any help at all is much appreciated, Thank you. 非常感谢您的任何帮助,谢谢。
I´d promote something like this: 我会宣传以下内容:
Make Cards
an interface
使Cards
成为interface
public interface Cards {
void print();
}
Make Guard
implement this interface and override the print
method there with the needed information. 使Guard
实现此接口,并在其中使用所需信息覆盖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
}
Now in the loop you just have to call 现在在循环中,您只需要调用
deck[i].print();
What is getting printed now will be depending on the actual implementation of what has to be printed, but in generall the class Cards
will know that it can print
now. 现在要打印的内容将取决于必须打印的内容的实际实现方式,但是一般来说, Cards
类会知道它现在可以print
。
Edit: Following @chrylis comment, your class should be called Card
instead of Cards
. 编辑:在@chrylis评论之后,您的班级应称为Card
而不是Cards
。 The reason here? 原因在这里吗? It´s like a simple plan for a single type of Card
(class here), but doesn´t represent multiple Cards
(multiple cards would be instances of Card
). 这就像是针对单一类型Card
的简单计划(此处为类),但并不表示多个Cards
(多个Card将是Card
实例)。
While some of the proposed solutions make sense in the narrow case (using a combination of instanceof
and casting the impacted Cards
element to Guard
in order to invoke printGuardInfo
), there might be a broader problem with the design of your inheritance. 尽管某些建议的解决方案在狭窄的情况下是有意义的(结合使用instanceof
和将受影响的Cards
元素强制转换为Guard
以便调用printGuardInfo
),但是继承的设计可能存在更广泛的问题。
Assuming Cards
is not really an empty class (otherwise the hierarchy does really not produce any benefit), my advice is to group your card objects under a common interface or abstract class (say, Card
), and have that interface provide an abstraction for general methods such as printInfo
, which is then implemented by each Card
type (you'd get the printGuardInfo
code inside the Guard
implementation there). 假设Cards
不是一个真正的空类(否则该层次结构实际上不会产生任何好处),我的建议是将您的card对象分组到一个通用接口或抽象类(例如Card
)下,并让该接口为通用提供抽象方法,例如printInfo
,然后由每种Card
类型实现(您将在其中的Guard
实现中获取printGuardInfo
代码)。
In turn, when iterating your array, you'd invoke printInfo
on each card, knowing that each and every child of Card
has its own printInfo
implementation, without the need to cast or use instanceof
. 反过来,在迭代数组时,您知道每个Card
子级都有其自己的printInfo
实现,而无需printInfo
转换或使用instanceof
, printInfo
在每个printInfo
上调用printInfo
。
您需要将Card
投掷给Guard
:
((Guard) deck[i]).printGuardInfo();
The easiest, most object-oriented way to do this is to change printGuardInfo
to toString
: 最简单,最面向对象的方法是将printGuardInfo
更改为toString
:
public String toString()
{
return new StringBuilder("This card score fo the guard is: ")
.append(cardScore).append('\n')
.append("The card name is: ")
.append(cardName).append('\n')
.append("The card ability is ")
.append(cardAbility)
.toString();
}
You can then call String guardInfo = deck[i].toString();
然后,您可以调用String guardInfo = deck[i].toString();
to get the guard info and write it to standard output, a logger, etc. 获取警卫信息并将其写入标准输出,记录器等
public String toString()
is inherited from Object
, so no casting is needed to call it. public String toString()
继承自Object
,因此无需强制转换即可调用它。
R2-D2 is right, but if you want to be more 'polymorphic' you should do something like This R2-D2是正确的,但是如果您想更“多态”,则应该执行以下操作
public interface ICard {
public void printInfo();
}
public class Card implements ICard{
public void printInfo(
System.out.println("Card Info");
}
}
public class Guard extends Card {
public void printInfo{
System.out.println("GUARD Info");
}
}
public vlass Deck{
...
public void addGuards()
{
for(int i=0; i<5; i++)
{
deck[i] = new Guard();
deck[i].printInfo();
}
}
}
Or even use an abstract class 甚至使用抽象类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.