Polymorphism in Java language

Description

With polymorphism we can call methods from class hierarchy using a uniform interface. The compiler will determine dynamically which implementation to use.

Dynamic Method Dispatch

When an overridden method is called through a superclass reference, Java determines which version of that method to execute.

Here is an example that illustrates dynamic method dispatch:

 
class Base {//w ww  .j  av a2  s.  co m
  void callme() {
    System.out.println("Inside A's callme method");
  }
}
class SubClass extends Base {
  void callme() {
    System.out.println("Inside B's callme method");
  }
}
class SubClass2 extends Base {
  void callme() {
    System.out.println("Inside C's callme method");
  }
}
public class Main {
  public static void main(String args[]) {
    Base a = new Base(); 
    SubClass b = new SubClass(); 
    SubClass2 c = new SubClass2();
    Base r; 
    r = a; 
    r.callme(); 
    r = b;
    r.callme(); 
    r = c; 
    r.callme();
  }
}

The output from the program is shown here:

Polymorphism Example

The following example uses the run-time polymorphism. It has three classes. The parent class is Shape. Rectangle and Triangle are both extending the Shape class. Shape defines a method called area() which returns the area of a shape. Both Rectangle and Triangle override area() method and provide their own version of implementation. When calling the area() method we can call it from the same object reference and Java compiler can figure out which area() method to use.

 
class Shape {/*from  w  ww .  j av a  2s.c  o m*/
  double height;
  double width;
  Shape(double a, double b) {
    height = a;
    width = b;
  }
  double area() {
    System.out.println("Area for Figure is undefined.");
    return 0;
  }
}
class Rectangle extends Shape {
  Rectangle(double a, double b) {
    super(a, b);
  }
  // override area for rectangle
  double area() {
    System.out.println("Inside Area for Rectangle.");
    return height * width;
  }
}
class Triangle extends Shape {
  Triangle(double a, double b) {
    super(a, b);
  }
  // override area for right triangle
  double area() {
    System.out.println("Inside Area for Triangle.");
    return height * width / 2;
  }
}
public class Main {
  public static void main(String args[]) {
    Shape f = new Shape(10, 10);
    Rectangle r = new Rectangle(9, 5);
    Triangle t = new Triangle(10, 8);

    Shape figref;

    figref = r;
    System.out.println("Area is " + figref.area());

    figref = t;
    System.out.println("Area is " + figref.area());

    figref = f;
    System.out.println("Area is " + figref.area());
  }
}

The output from the program is shown here:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures