Junior
What is the idea of polymorphism in programming?
sobes.tech AI
Answer from AI
Polymorphism is the ability of objects of different classes to respond to the same method in different ways. This is achieved through the use of the following mechanisms:
-
Method Overriding: A subclass changes the behavior of a method inherited from a superclass.
class Animal { public void sound() { System.out.println("Makes a sound"); } } class Dog extends Animal { @Override public void sound() { System.out.println("Bark"); } } -
Method Overloading: In one class, methods with the same name coexist but have different parameters (number or type).
class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } }
Polymorphism allows creating more flexible, extendable, and easily maintainable code. It enables working with objects through their base types, abstracting from the specific implementation.