What is inheritance?
- Inheritance is a key concept in object-oriented programming (OOP) that allows a class to inherit the properties and behaviours (methods and attributes) of another class
- Inheritance promotes code reuse by allowing derived classes to inherit and utilise the existing code from the base class. This avoids duplicating code and promotes better organisation and maintainability
- Inheritance establishes an “IS-A” relationship between the base class and the derived class
- For example, if you have a base class called
Vehicleand a derived class calledCar, you can say that “a Car is a Vehicle.” - The car class inherits the properties and behaviours associated with being a vehicle
- Inheritance involves two main entities:
- The base class (also known as the parent class or superclass) and the derived class (also known as the child class or subclass)
- The derived class inherits the characteristics of the base class, meaning it can access and use the methods and attributes defined in the base class
- If a car object was to be created, it may have the following attributes:
Manufacturer- The company that makes the carMake- The model of the carCost– The price of the car to purchaseIsInsured– Whether or not the car is insuredEngineCapacity– The size of the engine for the car
- It may also have access to the following methods:
TurnEngineOn()– To start the car engineTurnEngineOff()– To turn off the car engineSteerLeft()– To turn the car to the leftSteerRight()– To steer the car to the leftGearChange()– To change the gear of the carUnlockDoors()– To unlock the doors to the car
- The above methods are only a select few and there could be many more added for extra functionality
- In the following code, the super keyword is used in inheritance to refer to the superclass (Base class:
Vehicles) and access its members (methods, attributes, or constructors) from within the subclass (Derived Class:Cars)
Example of a base class and derived classes
Worked Example
The classes office and house inherit from building. Describe what is meant by inheritance with reference to these classes.
[2]
How to answer this question:
- 1 mark per bullet up to a maximum of 2 marks, e.g:
- When the child/derived/subclass class office/house takes on attributes/methods…
- … from building / parent/base/superclass/ class
Answer:
Example answer to get full marks: When the derived classes “office” and “house” inherit attributes/methods [1] from the “building” base class, they gain access to the properties and behaviours defined in the “building” class. [1]