Classes/Objects  «Prev 


Demonstration of 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.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in object oriented programming occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic.

Access an Object through Reference Variable

In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.It is important to know that the only possible way to access an object is through a reference variable.
  1. A reference variable can be of only one type and once declared, the type of a reference variable cannot be changed.
  2. The reference variable can be reassigned to other objects as long as it is not declared final.
  3. The type of the reference variable will determine the methods that it can invoke on the object.
  4. A reference variable can refer to any object of its declared type or any subtype of its declared type.
  5. A reference variable can be declared as a class or interface type.
The following example demonstrates the concept of polymorphism in Java.

Sub Class extends Base Class and overrides method accelerate()

class Car {
 public int gearRatio = 8;
 // accelerate method in Car
 public String accelerate() {
  return "Accelerate : Car";
 }
}

class SportsCar extends Car {
 public int gearRatio = 9;
 // accelerate method in  SportsCar
 public String accelerate() {
  return "Accelerate : SportsCar";
 }

 public static void main(String[] args) {
  Car c = new SportsCar();
  System.out.println(c.gearRatio + "  " + c.accelerate());
 }
}

Program Output:
8 Accelerate : SportsCar */

Method Overloading (Static Polymorphism)

Let us work with an example from the Java API classes that we all use frequently:
System.out.println(). The println method accepts multiple types of method parameters:
Figure 3-2: Real-life examples of overloaded methods
Figure 3-2: Real-life examples of overloaded methods

int intVal = 11;
boolean boolVal = false;
String name = "eJava";
System.out.println(intVal); // prints int Val
System.out.println(boolVal); // Prints a boolean value
System.out.println(name); //Prints a string value

When you use the method println, you know that whatever data type you pass to it as a method argument, the value will be printed to the console. Using method overloading, Java avoids have to create methods such as
  1. printlnInt,
  2. printlnBool, and
  3. printlnString.