<<< Is-a relationship     Index     Main Driver >>>

7. Polymorphism


  • Polymorphism stands for uniform interface .

  • Each derived class inherits the base interface.

  • Each derived class provides its own implementation of each method in the interface.

  • When uniform message (like draw) is sent to an object, it will respond in a distinct way.


  • Shape Java class:

    
    public abstract class Shape {
        private double area;
        public abstract double getArea();
    }
    
    
  • Shape UML diagram:

      Shape UML diagram


  • Rectangle Java class:

    
    public class Rectangle extends Shape{
        double length;
        double width;
    
        public Rectangle( double l, double w ) {
            length = l;
            width = w;
        }
    
        public double getArea() {
            area = length * width;
            return ( area );
        }
    }
    
    
  • Circle Java class:

    
    public class Circle extends Shape {
        double radius;
    
        public Circle( double r ) {
            radius = r;
        }
    
        public double getArea() {
            area = 3.14 * ( radius * radius );
            return ( area );
        }
    }
    
    
<<< Is-a relationship     Index     Main Driver >>>