What is polymorphism?
- Polymorphism is a concept in programming that allows objects to take on different forms or behaviours.
- Different objects can share the same name or behaviour but can work in different ways
- It helps make code more flexible, reusable, and easier to maintain
- It allows flexibility and reusability in programming, making it easier to write and manage code
- Objects can be treated as belonging to a common group, even if they belong to different classes, making your code more versatile and adaptable to changes
Example 1 – method overloading
Method Overloading Example 1
- In the example above, all three classes all have a method named
move(). Polymorphism allows methods to be declared with the same name but execute different code (in this case printing different messages) - The override keyword Is used to provide a new implementation for a method that is already defined in the parent class (base class)
Example 2 - method overriding
Method Overriding Example 2
- In the above example, both the Motorcycle class and the Car class inherit from the base class Vehicle
- Objects from the Motorcycle and Car classes can call the
startEngine()method, which will output “Engine Started!” - If either of the object types calls the
displayInfo()method, the program will execute the method from the object’s class, as it overrides the method from the Vehicle class - For example:
- If a Motorcycle object calls the
displayInfo()method, “I am a Motorcycle!” will be output - If a Car object calls the
displayInfo()method, “I am a Car!” will be output
- If a Motorcycle object calls the
Treating objects as common groups
- Polymorphism also allows objects of different classes to be treated as objects of a common superclass or base class
- For example:
Vehicle vehicle1 = new Car()Vehicle vehicle2 = new Motorcycle()
- This allows an array of type Vehicle to store both Motorcycle and Car objects rather than in separate data structures
- If the
vehicle1.displayInfo()method is called, it will still output “I am a Car!” - If the
vehicle2.displayInfo()method is called, it will still output “I am a Motorcycle!”
- If the
- This flexibility provided by polymorphism are essential for creating more maintainable and modular code