Java - Polymorphism

What is Polymorphism in Java

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language.

 

Remember any java object that can pass more than one IS-A test can be considered polymorphic.

 

Other than object of type object, all java objects are polymorphic in that they pass the IS-A test for their own type and for class object.

 

Polymorphism is an Oops concept which advice use of common interface instead of concrete implementation while writing code

 

When we program for interface our code is capable of handling any new requirement or enhancement arise in near future due to new implementation of our common interface. If we don't use common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation

 

How Polymorphism support in Java

Java has excellent support of polymorphism in terms of method overloading (compile time polymorphism) and method overriding (runtime polymorphism).

 

Example


public class A{
	public String getMessage(){
		return "calling A";
	}
}
public class B extends A{
	public String getMessage(){
		return "calling B";
	}
}

public class C extends A{
	public String getMessage(){
		return "calling C";
	}
}


 

Where to use Polymorphism in Java Code

let's look at OO design first, inheritance represents a IS-A relationship, generally we can say something like "let our FlyingMachines fly". every specific FlyingMachines (sub class) IS-A FlyingMachines (parent class), let say Jet, fits this "let our FlyingMachines fly", while we want this flying actually be the fly function of the specific one (sub class), that's polymorphism take over.

 

So we do things in abstract way, oriented interfaces and base class, do not actually depend on detail implementation, polymorphism will do the right thing!

 

Method Overloading (Static Binding or compile time polymorphism)

If a class have multiple methods by same name but different parameter is known as Method Overloading.

  • appear in the same class or a subclass
  • have the same name but,
  • have different parameter lists, and,
  • can have different return types

 

Advantage of Method Overloading

Method overloading increases the readability of program.

 

How to overload method

There are two way to overload the method.

  1. By changing number of arguments.
  2. By changing the data type of arguments.

Note: In Java, Method overloading is not possible with changing return type of methods.

 

Example:


public class Main{
	public void sum(int a, int b){
		System.out.println(a+b);
	}
	public void sum(int a, int b, int c){
		System.out.println(a+b+c);
	}

	public static void main(String args[]){
		Main test = new Main();
		test.sum(10,20);
		test.sum(10,20,30);
	}
}
		

 

Output:

30

60

 

Example:


public class Main{
	public void sum(int a, int b){
		System.out.println(a+b);
	}
	public void sum(double a, double b){
		System.out.println(a+b);
	}

	public static void main(String args[]){
		Main test = new Main();
		test.sum(10,20);
		test.sum(10.5,20.5);
	}
}
		

 

Output:

30

31.0

 

Method Overriding (Dynamic Binding or Runtime Polymorphism)

Having the same method in the subclass as declare in parent class is known as method overriding.

  • applies ONLY to inherited methods is related to polymorphism
  • object type (NOT reference variable type) determines which overriden method will be used at runtime
  • overriding method MUST have the same argument list (if not, it might be a case of overloading)
  • overriding method MUST have the same return type; the exception is covariant return (used as of Java 5) which returns a type that is a subclass of what is returned by the overriden method
  • overriding method MUST NOT have more restrictive access modifier, but MAY have less restrictive one
  • overriding method MUST NOT throw new or broader checked exceptions, but MAY throw fewer or narrower checked exceptions or any unchecked exceptions
  • abstract methods MUST be overridden
  • final methods CANNOT be overridden
  • static methods CANNOT be overridden
  • constructors CANNOT be overridden

 

Advantages of Method Overriding:

  • Time to invest method signature is reduced
  • Different functionality in both super class and sub class by sharing same signature
  • The functionality can be enhanced
  • The behavior can be replaced in the sub class
  • Method Overriding is used for Runtime Polymorphism

 

Example:


class superCls
{
    int y;
    superCls(int y)
    {
        this.y=y;
    }
    void display()
    {
        System.out.println("super y = " +y);
    }
}
class subCls extends superCls
{
    int z;
    subCls(int z , int y)
    {
        super(y);
        this.z=z;
    }
    void display()
    {
        System.out.println("super y = " +y);
        System.out.println("sub z = " +z);
    }

}

public class TestMethodOverride
{
    public static void main(String[] args)
    {
        subCls obj1 = new subCls (500,300);
        obj1.display();
    }
}