Polymorphism
 

- JavaTouch
- Java SE Home
- Java EE Home
- Java Design Home
- Design Patterns Home

What is polymorphism?

Literal meaning:
The meaning of the word polymorphism is something like one name, many forms.

OO programming meaning:
Polymorphism is the ability of a programming language to process object differently depending on their datatype or class.

Three distinct forms of polymorphism

From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:

    * Method overloading
    * Method overriding through inheritance
    * Method overriding through the Java interface

Polymorphysm (Method overloading)

This is the simplest form of Polymorphism. Here, a class declare two or many methods with same name but with different parameters type (i.e. different method signeture). When we call these same method with different parameters, it can behave differently. This is the simplest form of polymorphism which involves method overloading. Lets test this with a simple example;

public class Printer {

    public static void main(String[] args) {
        Printer printer = new Printer();
        // call the overloaded methods
        printer.doubledPrint(12);
        printer.doubledPrint("12");
    }

    /**
     * Print the doubled value
     * @param value
     */

    public void doubledPrint(int value) {
        System.out.println(value * 2);
    }

    /**
     * Print the value twise
     * @param value
     */
    public void doubledPrint(String value) {
        System.out.println(value + value);
    }
}

Output:
      24
      1212

Here we called the same method, but with different parametr types, then those behave differently. 
Note:
A valid overload differs in the number or type of its arguments.  Differences in argument names are not significant.  A different return type is permitted, but is not sufficient by itself to distinguish an overloading method.

Following are valid overloaded methods;

void doubledPrint(String value)
void doubledPrint(int value)
void doubledPrint(int value, int nextValue)
void doubledPrint(int value, String nextValue)

int doubledPrint(int value)  <= This is not considered to be overloaded because different in return type alone is not sufficient to be considered as overloaded. 

References:
- The Essence of OOP Using Java, Polymorphism and Interfaces, Part 1 

>> Next Page