| 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: 244
|
|
|
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: 32611
|
|
|
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: 1046
|
|
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.
|
 |
 |
|
|
subject: How to do it using Polymorphism now
|
|
|