Junior — Middle
What methods and tools are used in Java to implement the principle of polymorphism?
sobes.tech AI
Answer from AI
In Java, polymorphism is implemented in several ways:
-
Inheritance and method overriding (runtime polymorphism) — a base class declares a method, and subclasses override it with their own implementation. The method call depends on the actual type of the object at runtime.
-
Method overloading (compile-time polymorphism) — multiple methods with the same name but different parameters can be declared within a class.
-
Interfaces and abstract classes — allow declaring methods without implementation, which are then implemented in subclasses, providing polymorphic behavior.
Example of overriding:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Outputs "Bark"
}
}