Junior
What is polymorphism in Java?
sobes.tech AI
Answer from AI
Polymorphism in Java is the ability of an object to take many forms. It is an OOP concept that allows performing a single action in different ways. In Java, polymorphism is implemented through method overriding and method overloading.
Types of polymorphism in Java:
- Compile-time Polymorphism: Achieved through method overloading. The compiler determines which method to call based on the method signature (name, number, and types of arguments).
- Runtime Polymorphism: Achieved through method overriding. The Java Virtual Machine (JVM) determines which method to call based on the actual object type at runtime. This is also known as dynamic method dispatch.
Example of method overloading:
// Class with overloaded methods
class Calculator {
// Method for adding integers
public int add(int a, int b) {
return a + b;
}
// Method for adding floating-point numbers
public double add(double a, double b) {
return a + b;
}
}
Example of method overriding:
// Base class
class Animal {
// Method to make a sound
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Derived class inheriting from Animal
class Dog extends Animal {
// Overriding makeSound method
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
// Derived class inheriting from Animal
class Cat extends Animal {
// Overriding makeSound method
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
// Using runtime polymorphism
class Main {
public static void main(String[] args) {
Animal myAnimal1 = new Dog(); // Object of type Dog, reference of type Animal
Animal myAnimal2 = new Cat(); // Object of type Cat, reference of type Animal
myAnimal1.makeSound(); // Calls Dog's makeSound method
myAnimal2.makeSound(); // Calls Cat's makeSound method
}
}
Advantages of polymorphism:
- Flexibility and extensibility: Code becomes more flexible, allowing easy addition of new object types without modifying existing code.
- Reduced coupling: Enables interaction with objects at their interface or base class level, reducing dependency on specific implementations.
- Improved readability and maintainability: Code becomes more structured and understandable.
Ultimately, polymorphism is one of the key pillars of object-oriented programming, enabling the writing of more universal and easily maintainable code.