Sobes.tech
Junior — Middle

How is the mechanism of polymorphism achieved in Java and how to implement it in code?

sobes.tech AI

Answer from AI

In Java, polymorphism is achieved through inheritance and method overriding, as well as through interfaces. This allows objects of different classes to respond differently to the same method calls.

Example of implementing polymorphism:

class Animal {
    void sound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.sound(); // Outputs: Bark
        myCat.sound(); // Outputs: Meow
    }
}

Here, the sound() method is called on objects of type Animal, but the actual implementation executed corresponds to the real class of the object (Dog or Cat). This is polymorphism — one interface, many implementations.