Introduce Java Polymorphism and give examples
Java polymorphism is a core concept in object-oriented programming that allows methods to do different things based on the object that it is acting upon. It enables a single interface to represent different underlying forms (data types). Polymorphism can be achieved in Java through method overriding and method overloading.
Compile-time Polymorphism (Method Overloading): This occurs when multiple methods have the same name but different parameters (different type or number of parameters) within the same class.
Runtime Polymorphism (Method Overriding): This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method that gets executed is determined at runtime based on the object being referred to.
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of 2 and 3: " + math.add(2, 3)); // Calls the first add method
System.out.println("Sum of 2, 3, and 4: " + math.add(2, 3, 4)); // Calls the second add method
System.out.println("Sum of 2.5 and 3.5: " + math.add(2.5, 3.5)); // Calls the third add method
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal; // Declare an Animal reference
myAnimal = new Dog(); // Assign a Dog object
myAnimal.sound(); // Calls Dog's sound method
myAnimal = new Cat(); // Assign a Cat object
myAnimal.sound(); // Calls Cat's sound method
}
}
In the first example, we demonstrate compile-time polymorphism through method overloading. The add
method is defined multiple times with different parameter lists, allowing it to handle different types and numbers of inputs.
In the second example, we demonstrate runtime polymorphism through method overriding. The sound
method is defined in the Animal
class and overridden in the Dog
and Cat
subclasses. The method that gets executed is determined at runtime based on the actual object type (Dog
or Cat
) that the Animal
reference points to.
Polymorphism enhances flexibility and maintainability in code, allowing developers to write more generic and reusable code. It is a fundamental principle that supports the dynamic behavior of objects in Java.