wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes getAction Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "getAction" Watch "getAction" New topic
Author

getAction

John Valiant
Greenhorn

Joined: Mar 01, 2012
Posts: 26
Wondering why i cant invoke my getAction?

Complier says
PSt5.java:60: error: cannot find symbol
owner.pets[ 4 ].getAction();
^
symbol: method getAction()
location: class Pet
1 error





Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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.
John Valiant
Greenhorn

Joined: Mar 01, 2012
Posts: 26
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?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

John Valiant wrote:ok, i cant put it to Pet as its an abstract class.


You can still define the method in Pet. You can make it abstract or you can make it concrete. Abstract classes can have concrete methods.


So i have to cast it..what do you mean by it?How?


I don't think casting is the right approach here. If you want to learn about casting, google for something like java casting tutorial.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: getAction