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
Give some features of interface?
How do you compare arrays in java?
Can the garbage collection be forced by any means?
What are filterstreams?
What is instance example?
How can you say java is object oriented?
What are nested classes in java?
What is a static class in java?
Is it possible to define a method in java class but provide it’s implementation in the code of another language like c?
Can we clone singleton class in java?
What are 4 pillers of object orinted programming?
Difference between this() and super() ?
What are "class access modifiers" in Java?
What are the rules for variable declaration?
What is the use of jtable?