Polymorphism in Java: Master 2 Essential Types – Compile-Time and Runtime Explained

Polymorphism in Java

  • Polymorphism in Java is one of the fundamental concepts in Object-Oriented Programming (OOP), which allows objects to be treated as instances of their parent class rather than their actual class.
  • The word polymorphism comes from Greek, meaning “many forms.”
  • In Java, polymorphism allows a single action to behave differently based on the object that it is acting upon.
Polymorphism in Java
Polymorphism in Java

There are two main types of Polymorphism in Java:

  1. Compile-time Polymorphism (also known as Method Overloading)
  2. Runtime Polymorphism (also known as Method Overriding)

1. Compile-Time Polymorphism (Method Overloading)

  • Compile-time polymorphism, or method overloading, occurs when multiple methods with the same name exist in a class, but with different parameters (different number or types of parameters).
  • The correct method is determined at compile time based on the method signature.

Key Points:

  • The method name is the same, but the parameters differ.
  • It is resolved at compile time by the compiler.
  • Overloaded methods can have different return types, but the parameters must differ in type or number.

Example:

class Calculator {

// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values
public double add(double a, double b) {
return a + b;
}
}

public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();

// Calling overloaded methods
System.out.println(“Sum of two integers: ” + calculator.add(10, 20)); // 30
System.out.println(“Sum of three integers: ” + calculator.add(10, 20, 30)); // 60
System.out.println(“Sum of two doubles: ” + calculator.add(10.5, 20.5)); // 31.0
}
}

  • In the above example, the add method is overloaded three times with different parameter types and numbers. The correct version is chosen based on the arguments passed.

 

2. Runtime Polymorphism (Method Overriding)

  • Runtime polymorphism, or method overriding, occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
  • At runtime, the Java Virtual Machine (JVM) determines which method to call based on the actual object type (not the reference type).

Key Points:

  • Method in the subclass overrides a method in the parent class.
  • The method signature in both parent and subclass must be the same.
  • Overridden methods are resolved at runtime based on the object type (dynamic method dispatch).

Example:

// Parent class
class Animal {
// Method in parent class
public void sound() {
System.out.println(“Animal makes a sound”);
}
}

// Child class (inherits from Animal)
class Dog extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println(“Dog barks”);
}
}

// Another child class (inherits from Animal)
class Cat extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println(“Cat meows”);
}
}

public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Reference type is Animal
Animal myDog = new Dog(); // Reference type is Animal, but object type is Dog
Animal myCat = new Cat(); // Reference type is Animal, but object type is Cat

// Demonstrating runtime polymorphism
myAnimal.sound(); // Output: Animal makes a sound
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}

 

In this example:

  • sound() is overridden in both the Dog and Cat classes.
  • When the sound() method is called on the Animal reference, the actual method that is invoked is determined by the object type (i.e., the actual instance of the class at runtime), not by the reference type.

 

Benefits of Polymorphism in Java

  1. Code Reusability: The same interface can be used for different implementations, thus promoting code reuse.
  2. Flexibility: You can change the behavior of a method depending on the type of object without changing the code that calls the method.
  3. Maintainability: It’s easier to maintain the code when different classes implement a common interface or extend the same base class.

Difference between Compile-Time Polymorphism and Runtime Polymorphism:

AspectCompile-Time Polymorphism (Static Binding)Runtime Polymorphism (Dynamic Binding)
DefinitionThe method is resolved at compile time.The method is resolved at runtime.
Method ResolutionThe method to be invoked is decided by the compiler based on the method signature.The method to be invoked is decided by the JVM based on the actual object type.
Achieved ThroughMethod Overloading (same method name, but different parameters).Method Overriding (method in subclass overrides the method in superclass).
Binding TypeStatic Binding or Early Binding.Dynamic Binding or Late Binding.
FlexibilityLess flexible, as methods must differ by parameter type/number or both.More flexible, as methods can be overridden to provide specific behaviors at runtime.
PerformanceFaster execution as the method is resolved during compile time.Slower execution because method resolution occurs during runtime.
Inheritance RequiredNo, methods can be overloaded within the same class.Yes, requires inheritance (subclass and superclass relationship).
Method SignatureMethods have different signatures (different number/types of parameters).Methods must have the same signature (method name and parameters) in both superclass and subclass.
Overloading/OverridingInvolves Overloading (same method name, different parameters).Involves Overriding (same method name and parameters, but implementation differs).
Code ExampleMethod Overloading, e.g., add(int a, int b) and add(int a, int b, int c).Method Overriding, e.g., sound() in Animal, Dog, Cat classes.
Type of PolymorphismCompile-Time Polymorphism.Runtime Polymorphism.
Binding OccursAt compile time (before the program runs).At runtime (when the program is executing).
Method Signature ComparisonMethod signatures must differ in number or type of parameters.Method signatures must be identical in both parent and subclass.
Example in Codepublic int add(int a, int b) { ... } and public int add(int a, int b, int c) { ... }class Dog extends Animal { @Override public void sound() { ... } }
Method Overload/OverrideOverloading (same method name, different parameter list).Overriding (same method name, same parameter list, different implementation).
Access Modifier ImpactThe access modifier has no effect on overload resolution (but may affect visibility).The access modifier in overriding should be at least the same level of visibility as the overridden method.
Return TypeReturn type can vary in overloaded methods, but method signature must differ.The return type must be the same or covariant in the overridden method.

Leave a Comment