Polymorphism (OOP) (OCR A Level Computer Science)
Revision Note
Written by: Jamie Wood
Reviewed by: James Woodhouse
Polymorphism (OOP)
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 Overloading
Method Overloading Example 2
In the above example both the Motorcycle class and the Car class both inherit from the base class 'Cars'
Objects from the Motorcycle Class and the Car class can call the
startEngines()
method which will output"Engines Started!"
If either of the object types call the
displayInfo()
method, the program will execute the method from the objects class as it overrides the Vehicle class methodFor example
If a motorcycle object calls the
displayInfo()
method,"I am a Motorcycle!"
will be outputIf a Car object calls the
displayInfo()
method,"I am a Car!"
will be output
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!"
This flexibility provided by polymorphism are essential for creating more maintainable and modular code
Last updated:
You've read 0 of your 10 free revision notes
Unlock more, it's free!
Did this page help you?