aspose file tools*
The moose likes Beginning Java and the fly likes How to do it using Polymorphism now Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to do it using Polymorphism now" Watch "How to do it using Polymorphism now" New topic
Author

How to do it using Polymorphism now

Caglar Cataloglu
Greenhorn

Joined: Feb 06, 2010
Posts: 25
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 ?



Java Lover
Caglar Cataloglu
Greenhorn

Joined: Feb 06, 2010
Posts: 25
i think i should use 'instanceof' keyword. but do you think this is a good software design
mukesh pandey
Greenhorn

Joined: Apr 02, 2010
Posts: 22
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

Joined: Jul 11, 2010
Posts: 247

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.


SCJP 6 [SCJP - Old is Gold]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40059
    
  28
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

Joined: Mar 17, 2010
Posts: 1051

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.


SCJP6.0,My blog Ranchers from Delhi
Cody Long
Ranch Hand

Joined: Jan 01, 2009
Posts: 95
All you have to do is add the sing() method to the cat class.
For example:


The your AnimalTester method would look like this:


Duct tape is like the Force. It has a dark side, a light side, and it binds the whole universe together.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to do it using Polymorphism now