Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about polymorphism ??

 
ahmad mayahi
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
ahmad mayahi
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great
Thanks :-)
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic