Understand how different objects can be treated as instances of a common type.
Imagine a universal remote control: it has one 'Power' button, but it knows exactly how to turn on a TV, a stereo, or a lamp. How can one single button trigger completely different actions depending on what it's pointing at?
Polymorphism comes from the Greek words poly (many) and morph (form). In Computer Science, it refers to the ability of a single variable, function, or object to take on multiple forms. Specifically, it allows us to treat objects of different subclasses as if they belong to a single parent class. This is powerful because it lets us write code that doesn't need to know the specific 'flavor' of an object to interact with it. For example, if we have a parent class `Animal`, we can call `.makeSound()` on any animal without caring if it's a `Dog` or a `Cat`. The program decides which version of the method to run at runtime, a process called dynamic method dispatch.
1. Create a parent class `Animal` with a method `speak()`. 2. Create a subclass `Dog` that overrides `speak()` to print 'Woof!'. 3. Create a subclass `Cat` that overrides `speak()` to print 'Meow!'. 4. Use a parent reference: `Animal myPet = new Dog();`. 5. When you call `myPet.speak();`, the output is 'Woof!' because the computer looks at the actual object type () rather than the reference type ().
Quick Check
If a variable is declared as a 'Shape' but holds a 'Circle' object, which 'draw()' method will run: the one in Shape or the one in Circle?
Answer
The 'draw()' method in the Circle class will run due to dynamic method dispatch.
While inheritance represents an 'is-a' relationship (a Dog is an Animal), Interfaces represent a 'can-do' relationship. An interface is a 100% abstract blueprint that defines a set of methods a class must implement, without providing the code for them. This allows unrelated classes to share the same behavior. For instance, both a `Bird` and a `Plane` can implement a `Flyable` interface. They aren't related by blood, but they both 'contractually' agree to provide a `takeOff()` and `land()` method. This makes your code modular; you can swap a `Boeing747` for a `Pigeon` in your 'FlightSimulator' as long as both implement `Flyable`.
1. Define an interface `PaymentMethod` with a method `process(double amount)`. 2. Create a class `CreditCard` that implements `PaymentMethod` using bank APIs. 3. Create a class `CryptoWallet` that implements `PaymentMethod` using blockchain logic. 4. In your store, you can create an array: `PaymentMethod[] options = {new CreditCard(), new CryptoWallet()};`. 5. Loop through the array and call `.process(50.00)` on each. The store doesn't need to know how the money is moved, only that the object can process it.
Quick Check
What is the main difference between a Class and an Interface?
Answer
A class defines what an object is and how it works, while an interface only defines what an object can do (its behavior) without providing the implementation.
The true strength of polymorphism is revealed when managing large systems. Imagine a video game with 1,000 different entities: players, enemies, trees, and bullets. Instead of having 1,000 different lists, we can give every entity an interface called `GameObject` with an `update()` method. We then maintain a single `List<GameObject>`. Every frame, we loop through the list and call `entity.update()`. The physics engine doesn't need to know if it's updating a bullet or a tree; it just knows that everything in that list is a `GameObject` and therefore must have an `update()` method. This reduces code complexity from (where is the number of types) to a manageable .
1. Create an interface `SmartDevice` with `turnOn()` and `getPowerUsage()`. 2. Implement `LightBulb` (uses ), `AirConditioner` (uses ), and `SecurityCamera` (uses ). 3. Create a `SmartHome` class with a `List<SmartDevice>`. 4. Write a method `calculateTotalLoad()` that iterates through the list and sums the result of `getPowerUsage()`. 5. This system is 'future-proof': if you add a `SmartFridge` tomorrow, the `calculateTotalLoad()` method doesn't need to change at all!
Which keyword is used by a class to use an interface?
Why is polymorphism considered a 'clean code' practice?
A class can implement multiple interfaces at the same time.
Review Tomorrow
In 24 hours, try to explain the 'Universal Remote' analogy to a friend using the terms 'Interface' and 'Implementation'.
Practice Activity
Build a small program where an interface 'Movable' is implemented by a 'Car' and a 'Person'. Create a list of 'Movable' objects and make them all move in a single loop.