This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
As the error message is telling you, the class Pet does not have a getAction() method. All the compiler knows is that each element of that array is a reference to a Pet. It doesn't know that the actual object it's pointing to is a Goldfish. You have to either cast it to Goldfish, or pull the getAction() method up to the Pet class.
And if you end up casting, that means you need to know and care which specific classes are in the array, which means you probably have a design flaw, and it shouldn't be an array of Pet, and you shouldn't be mixing Goldfish and other Pets in it.
On the other hand, if you define the method in Pet--and you should only do so if it makes sense for all Pets to have a getAction() method--then you can mix different kinds of Pets in the array and you only ever have to know or care that each one is a Pet, without worrying about which specific kind of Pet.
Joined: Mar 01, 2012
ok, i cant put it to Pet as its an abstract class. So i have to cast it..what do you mean by it?How?