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
Are private methods final?
What is a qms manual?
What are exceptions
How does java enable high performance?
What is the difference between a synchronized method and a synchronized block?
Which is the best sorting technique in java?
why java does not support unsigned keyword?
What is a flag value?
What is locale?
Why java is called not pure object oriented language?
Can we have any code between try and finally blocks?
Can you call a method in a method?
What is an object in java and how is it created?
how do I create a runnable with inheritance? : Java thread
How do you sort a string in java?