<<< Polymorphic Operations     Index     Animation: Object Oriented Paradigm >>>

10. Polymorphism Example


  • Practical use of polymorphism - array of shape-derived objects, Circles, Rectangles, and Triangles:

    
    public abstract class Shape {
        public abstract void draw();
    }
    public class Circle extends Shape {
        public void draw() {
            System.out.println("I am drawing a Circle");
        }
    }
    public class Rectangle extends Shape {
        public void draw() {
            System.out.println("I am drawing a Rectangle");
        }
    }
    public class Triangle extends Shape {
        public void draw() {
            System.out.println("I am drawing a Triangle");
        }
    }
    
    
  • 
    public class TestShapeArray {
        public static void main( String args [] ) {
            Shape [] myshapes = new Shape [4];
            myshapes [0] = new Circle();
            myshapes [1] = new Rectangle();
            myshapes [2] = new Circle();
            myshapes [3] = new Triangle();
            System.out.println(myshapes[0].draw());
            System.out.println(myshapes[1].draw());
            System.out.println(myshapes[2].draw());
            System.out.println(myshapes[3].draw());	
        } // end of main
    } // end of TestShapeArray 
    
    
  • Test Results:

        I am drawing a Circle
        I am drawing a Rectangle
        I am drawing a Circle
        I am drawing a Triangle   
    
<<< Polymorphic Operations     Index     Animation: Object Oriented Paradigm >>>