Sobes.tech
Junior — Middle

How is the mechanism of polymorphism achieved in Java?

sobes.tech AI

Answer from AI

In Java, polymorphism is achieved through inheritance and interface implementation, allowing objects of different classes to be processed 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 output "Bark" thanks to polymorphism
    }
}
How is the mechanism of polymorphism achieved in… - sobes.tech