Junior — Middle
Kuidas saavutatakse Java-s polümorfismi mehhanism?
sobes.tech AI
Vastus AI-lt
In Java, polymorphism is achieved through inheritance and interface implementation, allowing objects of different classes to be treated through a common type. The main mechanisms:
- Method overloading (compile-time polymorphism) — methods with the same name but different parameters.
- Method overriding (runtime polymorphism) — a subclass overrides a superclass method, and the method call is determined at runtime.
Example:
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(); // Will print "Bark" thanks to polymorphism
}
}