Polymorphism in Object-Oriented Programming
Polymorphism: The Fourth Principle of Object-Oriented Programming
Definition
- Polymorphism means "many forms."
- It's a feature in object-oriented programming languages that allows an object to take different forms.
Demonstration
- Creating a
Checkbox class that extends UIControl. - Addressing the constructor issue in
UIControl by commenting out the parameterized constructor to avoid immediate complications related to calling the base constructor using the super keyword.
Problem: Rendering Control Objects (Procedural Approach)
- Creating a
UIControl array to hold different control objects (e.g., TextBox, Checkbox). - The procedural way involves a large
if statement to determine the type of control and call the appropriate render method. - Problem: Every time a new control class is added, the
if statement needs modification, violating the Open/Closed Principle.
Polymorphism Solution
- Adding a generic
render method to the UIControl class.java
public void render() {
// No implementation here
}
- This method has no implementation in the
UIControl class because the rendering logic depends on the specific control type. - Overriding the
render method in subclasses (e.g., TextBox, Checkbox).
Implementation in Subclasses
- Overriding the
render method in the TextBox class:java
@Override
public void render() {
System.out.println("Render TextBox");
}
- Overriding the
render method in the Checkbox class:java
@Override
public void render() {
System.out.println("Render Checkbox");
}
- Each subclass has its own rendering algorithm, demonstrating the encapsulation principle.
Encapsulation
- Bundling data and operations around data inside a single unit (class).
- Instead of having multiple render methods (e.g.,
renderTextBox, renderCheckbox), each class has its own render method.
Polymorphism in Action (Main Class)
- Iterating over the
controls array and calling the render method on each control object. java
for (UIControl control : controls) {
control.render();
}
- At compile time, the array is declared as an array of
UIControl objects, but at runtime, it contains different types of objects (TextBox, Checkbox). - Each object has its own
render method, allowing the control object to take many different forms (polymorphism).
Example
- An array of
UIControl objects containing a TextBox and a Checkbox. - Iterating through the array and calling
render on each object. - The appropriate
render method for each object is called based on its actual type at runtime.
Benefit
- Reduces the if statement and allows the user to avoid modifications when new classes are added
Summary
- Polymorphism allows objects to take on multiple forms, enabling more flexible and maintainable code.
- It works in conjunction with inheritance and encapsulation to achieve object-oriented programming principles.