what is polymorphism with example?types of polymorphism?
Answer Posted / amr
well Polymorphism means one name implies many forms , which introduces generic programming . Polymorphism happens in the inheritance hierarchy , so that low level abstractions which extend higher level abstraction can override
(re-implementing a method of superclass in a subclass with identical signature) the implementation of the higher level abstraction .
example :
class vehicle {
void accelerate()
}
class car extends vehicle{
void accelerate()
{
S.O.P("um a car");
}
}
class bike extends vehicle{
void accelerate()
{
S.O.P("um a bike");
}
}
now bike and car vehicles .
so we can say
Vehicle[] v = new Vehicle[2];
v[0]= new Car();
v[1]=new Bike();
so here i have array of vehicles
i can do the following (generically )
for (i=0;i<v.length;i++)
v[i].accelerate();
-------
output:
um a car
um a bike
like i say ok guys all of u r vehicles so all of u can accelerate so do it everyone on his own way .
now that was a very polymorphic piece of code
because every time i call the method accelerate on an object the JVM will do Dynamic resolution and invoke the corresponding method of that object .
so not only overriding is polymorphic but we should keep a consistent inheritance hierarchy or abstraction levels .
---
method overloading is another form of polymorphism but its easier to implement because at compilation time all the method calls are resolved .
for ex
-----
class Add {
int add(int a, int b)
{
return a+b;
}
float add(float a,float b)
{
return a+b;
}
}
so be careful with overloading because methods are identified by it signature which is
-return type
-name
-parameters number
-parameters types
-order of parameters
since overloading means the same name then we are left with
-return type
-parameters number
-parameters types
-order of parameters
now lets see this code
Add a = new Add();
int x =a.add( 2 , 3 );
float y = a.add( 2.2, 3.4);
-----------
now i guess this covers the polymorphism types
what do u say
Is This Answer Correct ? | 39 Yes | 16 No |
Post New Answer View All Answers
What is a linkedhashmap java?
If an object is garbage collected, can it become reachable again?
What is mvc in java?
Define reflection.
What is an image buffer?
What is package private scope in java?
What are the main uses of java?
When will we prefer to use set and list in java and why?
Is null a string or object in java?
What is jee6?
What is difference between printf and scanf?
What is the purpose of java?
why java uses class level type casting ?
Hi friends am new to java. I read jar file means collection of java files. For executing struts application what are the necessary jar files. " struts.jar " file contains what. can u explain
Can a source file contain more than one class declaration?