Java Polymorphism

Polymorphism is a feature which allows a method to perform different things based on the object on which it is acting upon. Which mean you can have multiple implementations of a single interface. Any object which can pass multiple (more than one) IS-A test is considered a polymorphic object.

In java an object can only be accessed through a reference variable which can be of a single type. The type of a reference variable cannot be changed. The reference variable type determines which methods it can invoke on an object.

Java Polymorphism Example

class Bike{
int maxSpeed = 110;

class SuzukiBike extends Bike{
int maxSpeed = 120;

public static void main(String args[]){
Bike b = new SuzukiBike();
System.out.println(“The maximum speed of bike is = ” + b.maxSpeed);


The maximum speed of bike is = 110

Java Upcasting

When an object of a sub class type is assigned to the reference variable of a super class is called upcasting. Example:

class JavaParent{
//parent class body
class JavaChild extend JavaParent{
//child class body

JavaParent p = new JavaChild();

The method overloading and method overriding demonstrates different types of polymorphism in java. These concepts were discussed previously.