Polymorphism in Java With Example
Polymorphism in Java With Example
Types of polymorphism and method overloading & overriding are covered in the
separate tutorials. You can refer them here:
1. Method Overloading in Java – This is an example of compile time (or static
polymorphism)
2. Method Overriding in Java – This is an example of runtime time (or dynamic
polymorphism)
3. Types of Polymorphism – Runtime and compile time – This is our next tutorial
where we have covered the types of polymorphism in detail. I would recommend
you to go though method overloading and overriding before going though this
topic.
Neigh
Cat.java
public class Cat extends Animal{
@Override
public void sound(){
System.out.println("Meow");
}
public static void main(String args[]){
Animal obj = new Cat();
obj.sound();
}
}
Output:
Meow
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first method
has 1 int parameter,
second method has 2 int parameters and third one is having double parameter.
Which method is to be called is determined by the arguments we pass while
calling methods. This happens at runtime compile time so this type of
polymorphism is known as compile time polymorphism.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25