Search Logic Blocks

Tuesday, June 23, 2020

Java: What is Polymorphism?

Polymorphism means many forms in Latin / Greek. In java, you can use the same method name but different implementations altogether. Like same action happens, but in different ways for the different objects. The purpose of the method is same but it behaves in different ways depending on passed variables / objects (compile time decision) or method is called by which object (run-time decision). Like when we add two numbers - numbers can be integers, floats, doubles. So, methods will be written differently for all the data types. Here in the following two methods, same action is taken but methods are different for different data types - int and double -
// add method adds two integer numbers and returns an integer number
public int add(int x, int y) {
return x + y;
}

// add method adds two double numbers and returns a double number
public double add(double x, double y) {
return x + y;
}
Polymorphism is of two types - Compile Time Polymorphism (Static Polymorphism) and Run Time Polymorphism (Dynamic Polymorphism)

Static Polymorphism
When we declared two or more methods with the same name but with different signatures (different parameters), it is decided at compiler time that which method will be invoked when called. That's why this type of polymorphism is called the compile time polymorphism. This polymorphism can be achieved by using Method Overloading feature in Java. Here is the example for Method Overloading -

Class MultiplyOverload (MultiplyOverload.java)
// Class MultiplyOverload with four overloaded methods multiply()
public class MultiplyOverload {
// Multiplies two integer numbers
public double multiply(int x, int y) {
int r = x * y;
return r;
}

// Multiplies one double number and one integer number
public double multiply(double x, int y) {
double r = x * y;
return r;
}

// Multiplies two double numbers
public double multiply(double x, double y) {
double r = x * y;
return r;
}

// Multiplies two double numbers and round off decimals if third boolean parameter is true
public double multiply(double x, double y, boolean ro) {
double r = 0.0;
if(ro) r = Math.round(x * y);
else r = x * y;
return r;
}
}
Class MultiplyOverloadTest (MultiplyOverloadTest.java)
// Class MultiplyOverloadTest to test overloaded methods multiply() in class MultiplyOverload
public class MultiplyOverloadTest {
public static void main(String args[]) {
MultiplyOverload mo = new MultiplyOverload();

System.out.println("9 * 8 = " + mo.multiply(9, 8)); // Calls first method
System.out.println("9.25 * 8 = " + mo.multiply(9.25, 8)); // Calls second method
System.out.println("9.25 * 8.75 = " + mo.multiply(9.25, 8.75)); // Calls third method
System.out.println("round(9.25 * 8.75) = " + mo.multiply(9.25, 8.75, true)); // Calls fourth method
}
}
Output:

9 * 8 = 72.0
9.25 * 8 = 74.0
9.25 * 8.75 = 80.9375
round(9.25 * 8.75) = 81.0

Dynamic Polymorphism
When we declare two or more methods with the same name and the same signatures too, the compiler is not able to resolve which method is to be called. So, in this case, decision to call one of the same name methods is made at run-time. That's why this kind of polymorphism is called as the run time polymorphism. This polymorphism can be achieved by using Method Overriding feature in Java.

Method overriding feature is connected with the inheritance principle in Java. (I will cover inheritance in detail in the next post.) In short, it is a parent-child concept. A class can be a parent of other classes and the classes inherited are called child classes or sub classes. A parent class and child class can have same name methods with same signatures (same number of parameters, same data types parameters and same return type). It is called Method Overriding. Here is the example of Method Overriding -

Class Shape (Shape.java)
// Parent class Shape
import java.lang.Math; // imports Math package
public class Shape {
final static double PI = Math.PI;
double width = 0;
double height = 0;

// Returns the text telling what shape it is
public String whatShape() {
return "";
}

// Returns the area of the shape
public double area() {
return 0.0;
}
}
Class Circle (Circle.java)
// Child class Circle inherits from class Shape
public class Circle extends Shape{
// Returns the text telling what shape it is
public String whatShape() {
return "Circle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
double radius = width / 2;
return Math.round(PI * radius * radius * 100) / 100.0;
}
}
Class Triangle (Triangle.java)
// Child class Triangle inherits from class Shape
public class Triangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
Class Rectangle (Rectangle.java)
// Child class Rectangle inherits from class Shape
public class Rectangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Rectangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round(height * width * 100) / 100.0;
}
}
Class ShapesTest (ShapesTest.java)
// class ShapesTest to test class Shape's overridden methods - whatShape() and area()
public class ShapesTest {
public static void main(String args[]) {
// Created an array of 3 shapes
Shape shapes[] = new Shape[3];

// Created 3 instances of 3 child classes
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Rectangle();
System.out.println("Shapes Test");

for(int i = 0; i < shapes.length; i++) {
shapes[i].height = 5;
shapes[i].width = 9;

// Called the methods through parent's reference (Compiler doesn't know which object's method is called)
// At run-time decision is made, which class method is called
System.out.println("Shape is " + shapes[i].whatShape());
System.out.println("Area is " + shapes[i].area());
System.out.println("");
}
}
}
Output:

Shapes Test
Shape is Circle
Area is 63.62

Shape is Triangle
Area is 22.5

Shape is Rectangle
Area is 45.0

No comments: