Junior
What is the idea of polymorphism in programming?
sobes.tech AI
Answer from AI
Polymorphism allows objects of different classes that share common features to be treated as objects of a common base type. This means "many forms" – the same method can have different behaviors depending on the actual type of the object on which it is called.
Key aspects:
- Inheritance: Polymorphism is closely related to inheritance. Child classes inherit methods and properties from the parent class and can override them for their specific implementation.
- Method Overriding: This is the primary mechanism of polymorphism at runtime. A child class provides its own implementation of a method already defined in the parent class.
- Compile-time Polymorphism or Method Overloading: Different methods with the same name but different signatures (different number or types of parameters). The compiler determines which method to call based on the signature.
- Type Casting: The ability to refer to a subtype object through a reference to its supertype. The actual type of the object determines which method will be called when invoking a polymorphic method.
Example with method overriding:
// Base class
class Animal {
public void makeSound() {
System.out.println("General animal sound");
}
}
// Derived class Dog
class Dog extends Animal {
@Override // Annotation for explicit override
public void makeSound() {
System.out.println("Woof!");
}
}
// Derived class Cat
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
// Usage example
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog(); // Type casting
Animal myCat = new Cat(); // Type casting
myAnimal.makeSound(); // Outputs "General animal sound"
myDog.makeSound(); // Outputs "Woof!" - polymorphic call
myCat.makeSound(); // Outputs "Meow!" - polymorphic call
}
}
Advantages of polymorphism:
- Flexibility and extensibility: Allows writing more general and reusable code. It is easy to add new types without changing existing code that works with the base type.
- Improved readability and maintainability: The code becomes more understandable as it abstracts from specific implementations.
- Reduction of code duplication: Common logic can be implemented in the base class, while specific logic can be in derived classes.
Thus, polymorphism in Java allows working with class hierarchies in a uniform manner, providing flexibility and the ability to extend the system.