Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to do it using Polymorphism now

 
Caglar Cataloglu
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So;

I have lots of animal classes and a Cat class all extending Animal class. But i have a few more special functions just for cats, like sing() function. So how can i call sing function ?

 
Caglar Cataloglu
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think i should use 'instanceof' keyword. but do you think this is a good software design
 
mukesh pandey
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use following code


void AnimalTest(Animal animal)
{
animal.eat(); //no problem with that, all animals eat
if(animal instanceof Cat){ // it check if the animal reference variable have cat as object or animal if cat then it allowes it to go in and the you can invoke sing menthod on cat
cat c = (cat)animal;
c.sing()

}
}
 
Ram Narayan.M
Ranch Hand
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can define the special functions in an "Interface". Rather restricting with "Cat" class, You can make "AnimalTest()" method generic one for animals which can sing.
 
Campbell Ritchie
Sheriff
Posts: 48402
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sounds a good idea about the interface, but maybe you would like to give links to tutorials about generic methods and interfaces.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Caglar Cataloglu wrote:So;

I have lots of animal classes and a Cat class all extending Animal class. But i have a few more special functions just for cats, like sing() function. So how can i call sing function ?



i think instance of test will only solve your problem that your program will not throw any runtime exception
So,Remember
for overloaded method refernce type determine which method to call.
but for overridden methods objects type define determines which method to call.

As you are talking about polymorphism ,overloaded method doesnot comes into picture then,
so you can make an object of appropriate type to call your overridden method.
 
Cody Long
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All you have to do is add the sing() method to the cat class.
For example:


The your AnimalTester method would look like this:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic