Sobes.tech
Junior — Middle

What advantages does polymorphism in Java offer?

sobes.tech AI

Answer from AI

Polymorphism in Java allows objects of different classes to respond to the same method call in different ways. This provides the following advantages:

  • Simplification of code: you can write general code without worrying about specific object types.
  • Extensibility: easily add new classes with their own method implementations without changing existing code.
  • Increased flexibility and reusability of code.

Example:

interface Animal {
    void sound();
}

class Dog implements Animal {
    public void sound() { System.out.println("Bark"); }
}

class Cat implements Animal {
    public void sound() { System.out.println("Meow"); }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound(); // Bark
        a = new Cat();
        a.sound(); // Meow
    }
}
What advantages does polymorphism in Java offer? — Java - sobes.tech