The moose likes Beginning Java and the fly likes a question about polymorphism ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a question about polymorphism ??" Watch "a question about polymorphism ??" New topic
Author

a question about polymorphism ??

ahmad mayahi
Greenhorn

Joined: May 10, 2009
Posts: 19
Hello
I'm a new programmer in JAVA. I immigrated from PHP to JAVA :-)
I have a question about Polymorphism.
I don't know what's wrong with my code! Why i can't access to my child class from the parent class by Polymorphism.
Code:
Main class:



Animal Class:


Dog Class:



Cat Class:


Any idea please?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19784
    
  20

Declare method eat() in class Animal as well. In Java, a method (or field) must be present in the reference class. Although the actual methods are Dog and Cat instances, the compiler doesn't know - all it knows is that they are Animal objects. And in your example Animal does not have the eat() method, so the compiler won't allow you to call it.

Of course, if you don't want to provide an implementation (i.e. method body), you can make both the class and the method abstract:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
ahmad mayahi
Greenhorn

Joined: May 10, 2009
Posts: 19
Your answer is great! Because i know now what's the abstract classes exactly.
Thanks a lot
But i don't know why the writer of "The joy of JAVA" book isn't explained it :S
He just wrote you can access to the subclasses from the super class :S
ahmad mayahi
Greenhorn

Joined: May 10, 2009
Posts: 19
Can you explain how can i passing an object to other method as a parameter and how can i use it in this method?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19784
    
  20

Check out http://www.javaranch.com/campfire/StoryPassBy.jsp; there is a little example at the bottom. The body of doStuff is not good though; you could do something like this:
ahmad mayahi
Greenhorn

Joined: May 10, 2009
Posts: 19
Great
Thanks :-)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a question about polymorphism ??