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 constructor and virtual function? Can we call a virtual function in a constructor?
Can you declare an interface method static?
Can we create a constructor in abstract class?
Why do we need strings in java?
Differentiate between postfix and prefix operators in java.
What are predicates in java 8?
Explain about oops concepts.
What are disadvantages of java?
Can inner class extend any class?
What is a stringbuilder?
What is predicate in java?
How many wrapper classes are there in java?
What are the different approaches to implement a function to generate a random number?
Difference between error and exception
What data type is a string?