next up previous contents
Next: Inheritance 2: Method Overriding Up: Java Notes Previous: Inheritance 1: Basic Example

Polymorphism & Dynamic Binding Example

/**
 * l1PolyTest.java: 
 * Polymorphism & dynamic binding Example 
 * Overridden area(double) defintions for Circle & Square
 **/

abstract class Shape{
  protected final static double PI = 22.0/7.0;
  protected double length;
  public abstract double area();
}

class Square extends Shape{
  Square(double side){
	length=side;// initialises inherited length
  }
  public double area(){// overrides area() of Shape
	return length*length;// length inherited from Shape
  }
}

class Circle extends Shape{
  Circle(double radius){
	length=radius;// initialises inherited length
  }
  public double area(){// overrides area() of Shape
	return PI*length*length;// PI & length inherited from Shape
  }
}

/**
 * Polymorphism & Dynamic binding test class
 **/
public class l1PolyTest{
  public static void main(String[] args){
	Shape sh;// no object instance just variable declaration
	Square sq = new Square(10.0);// sq is a Square object reference 
	Circle circ = new Circle(10.0);// circ is a Circle object reference

	sh=sq;// sh dynamically bound to the Square object referenced by sq
	System.out.println("Area of Square = " + sh.area());

	sh=circ; // sh dynamically bound to the Circle object referenced by circ
	System.out.println("Area of circle = " + sh.area());
  }
}
/*********** Compile & Run **************
# javac l1PolyTest.java
# java l1PolyTest
Area of Square = 100.0
Area of circle = 314.2857142857143
# 
****************************************/



Ananda Amatya
9/15/1999