Saturday, July 12, 2014

java - Polymorphism



The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.


class Shape {

    public void area() {
        System.out.println("Shape area");
    }
}

class Circle extends Shape {

    public void area() {
        System.out.println("Circle area");
    }
}

class Square extends Shape {

    public void area() {
        System.out.println("Square area");
    }
}





class RunPol {

    public static void main(String[] args) {
        Shape[] shape = new Shape[2];
        shape[0] = new Circle();
        shape[1] = new Square();

        for (int i = 0; i < shape.length; i++) {
            Shape sh = shape[i];
            sh.area();
        }

    }
}

Note that the area() method is overridden.


output:
Circle area
Square area

The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.





No comments:

Post a Comment