Junior — Middle
What approaches and techniques of polymorphism are available in Java, and how are they implemented?
sobes.tech AI
Answer from AI
In Java, polymorphism is implemented in two main ways:
- Runtime polymorphism (dynamic polymorphism) — achieved through method overriding. When you have a reference to a base class but the object actually belongs to a derived class, the version of the method in the derived class is called.
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
Animal a = new Dog();
a.sound(); // Will output "Bark"
- Compile-time polymorphism (static polymorphism) — implemented through method overloading, where multiple methods in the same class have the same name but different parameters.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Thus, Java supports polymorphism through inheritance and interfaces, allowing objects of different classes to use the same interface with different implementations.