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.
The array is of type 'Cards' and is instantiated in the Deck class.
The Cards class is pretty much empty:
public class Cards {
}
The object being stored in the array is of type Guard. Here is the Guard class and it's state and methods:
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. I am then filling a array of type Cards with objects of type Guard.This is polymorphism, I believe.
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].
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.
instanceofandcasting?Cardinstead ofCards.