1.2.3 Polymorphism
Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. This enables methods to be written that can work with objects of multiple types.
Key Concepts
1. Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows the subclass to provide its own behavior while still maintaining the interface defined by the superclass.
Example:
class Animal { void makeSound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void makeSound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void makeSound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.makeSound(); // Output: Dog barks myCat.makeSound(); // Output: Cat meows } }
2. Method Overloading
Method overloading occurs when a class has multiple methods with the same name but different parameters. The compiler determines which method to call based on the arguments provided.
Example:
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // Output: 15 System.out.println(calc.add(5.5, 10.5)); // Output: 16.0 } }
3. Polymorphic Arrays and Collections
Polymorphism allows arrays and collections to hold objects of different subclasses, providing flexibility and reducing code duplication.
Example:
class Shape { void draw() { System.out.println("Drawing a shape"); } } class Circle extends Shape { @Override void draw() { System.out.println("Drawing a circle"); } } class Square extends Shape { @Override void draw() { System.out.println("Drawing a square"); } } public class Main { public static void main(String[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new Circle(); shapes[1] = new Square(); for (Shape shape : shapes) { shape.draw(); } // Output: // Drawing a circle // Drawing a square } }
Analogies
Think of polymorphism as a universal remote control that can operate different devices (TV, DVD player, etc.) using the same buttons but with different behaviors. Each device implements the same interface (buttons) but provides its own specific functionality.
Another analogy is a shape-drawing tool that can draw different shapes (circle, square, triangle) using the same "draw" command. Each shape implements the "draw" method but provides its own specific drawing logic.
Understanding polymorphism enhances your ability to write flexible, reusable, and maintainable code, making it a crucial concept for any Java developer.