Polymorphism in Java with example

Polymorphism is a concept in java programming in which we can do one action in different ways. The word polymorphism itself says “many forms”. We mainly have two types of polymorphism static polymorphism and dynamic polymorphism which are also called compile time polymorphism and runtime polymorphism. We achieve polymorphism in java by method overloading and method overriding. We use method overloading for static polymorphism and method overriding for dynamic polymorphism. We’ve already discussed about method overloading in previous article, so we will concentrate on run time polymorphism in this article.

If we declare a method in subclass that is already present in super class then it is known as method overriding. Of course there are advantages of method overriding. It allows a class to implement the inherited method in it’s own way.

Some of the rules that should be followed in method overriding are as follows:

  1. The list of arguments in overriding method must always be same as that of method of super class. The order and datatype should be maintained.
  2. The access modifiers of the overriding methods can be more restrictive than that of the superclass method but the reverse is not true. A protected method in superclass cannot be public in subclass.
  3. The three types of methods: private, static and final cannot be overridden as the belong to a certain class only (i.e. they are local to a specific class).
  4. Dynamic Binding: The overridden methods are binded at runtime which is known as dynamic binding.

Now let us do an example to show how we can achieve runtime polymorphism in java by method overriding.


class District{

public double getArea(){

return 0.00;

}

}

class Dang extends District{

public double getArea(){

return 3456.25;

}

}

class Rukum extends District{

public double getArea(){

return 3125.78;

}

}

public class DistrictArea{

public static void main (String[] args){

Dang dang = new Dang();

Rukum rukum = new Rukum();

System.out.println("The area of Dang is: "+dang.getArea+" The area of Rukum district is: " +rukum.getArea());

}

}

Output:

The are of Dang is: 3456.25 The area of Rukum district is: 3125.78

In this way we have overridden the method getArea() in two different child class Dang and Rukum.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s