What is polymorphism in object-oriented programming (OOP)?
sobes.tech AI
Answer from AI
Polymorphism in OOP is the property of objects to behave differently depending on their type, allowing the use of the same interface (method) to handle different data types. This provides flexibility and extensibility of the code.
Main types of polymorphism:
-
Compile-time polymorphism (static): Implemented through method overloading. Different methods have the same name but differ in the set and/or types of parameters. The compiler determines which method to call based on the call signature.
class Calculator { // Overloading the add method public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } } -
Runtime polymorphism (dynamic): Implemented through method overriding. A subclass provides its specific implementation of a method that is already defined in the superclass. The specific implementation is chosen at runtime based on the actual object type.
class Animal { // Base method public void sound() { System.out.println("The animal makes a sound"); } } class Dog extends Animal { // Overriding the sound method @Override public void sound() { System.out.println("The dog barks"); } } // Example usage // Animal myDog = new Dog(); // Actual object type - Dog // myDog.sound(); // Calls the sound method from the Dog class
Polymorphism allows writing more abstract and clear code that describes the subject area, simplifies support, and adds new features without changing existing code. In the context of QA and QA Automation, understanding polymorphism is important for working with automation frameworks that use abstract classes/interfaces and their concrete implementations (for example, when working with drivers for different browsers in Selenium).