Junior — Middle
What is the difference between static and dynamic polymorphism in the context of object-oriented programming?
sobes.tech AI
Answer from AI
Static polymorphism (compile-time polymorphism) is implemented through method and operator overloading, where the specific version of a method is chosen during compilation. This allows the same method to be used with different parameters.
Dynamic polymorphism (run-time polymorphism) is achieved through method overriding in inherited classes and the use of virtual methods. The specific implementation of a method is selected at runtime, allowing objects to behave differently depending on their actual type.
Example of static polymorphism:
class Calculator {
int sum(int a, int b) { return a + b; }
double sum(double a, double b) { return a + b; }
}
Example of dynamic polymorphism:
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"