B3.2.1Inheritance — Superclasses, Subclasses and Code Reusability
0/7
B3.2 Fundamentals of OOP for multiple classesB3.2.1

Inheritance — Superclasses, Subclasses and Code Reusability

Explain and apply the concept of inheritance in OOP to promote code reusability

AHL≈ 60 minCommand term: ExplainFree lesson

In this lesson

  • Explaining how inheritance creates a hierarchy of parent (super) and child (sub) classes
  • Extending an existing class in Java and Python, including calling the superclass constructor
  • Explaining the effect of private, default, protected and public on access from subclasses and other classes
  • Explaining how inheritance promotes code reuse

LearnIs a

    0 of 4

    LearnInheritance in UML

    Vehicle
    • - reg: String
    • # wheels: int
    • + Vehicle(reg: String, wheels: int)
    • + getReg(): String
    • + describe(): String
    Bus
    • - seats: int
    • + Bus(reg: String, seats: int)
    • + getSeats(): int
    Motorbike
    • - engineCc: int
    • + Motorbike(reg: String, engineCc: int)
    • + getEngineCc(): int
    • BusVehicleBus inherits from (is a) Vehicle
    • MotorbikeVehicleMotorbike inherits from (is a) Vehicle

    The subclasses list only what they add. The hollow triangle points to the superclass.

    CodeExtending a class

    class Vehicle:
    def __init__(self, reg, wheels):
    self.__reg = reg
    self._wheels = wheels
    def getReg(self):
    return self.__reg
    def describe(self):
    return self.__reg + " has " + str(self._wheels) + " wheels"
    class Bus(Vehicle):
    def __init__(self, reg, seats):
    super().__init__(reg, 6) # the Vehicle constructor sets reg and wheels
    self.__seats = seats
    def getSeats(self):
    return self.__seats
    b = Bus("S-BU 42", 70)
    print(b.describe()) # inherited from Vehicle
    print(b.getReg(), "seats", b.getSeats())
    Output
    S-BU 42 has 6 wheels
    S-BU 42 seats 70

    Bus has no describe or getReg of its own: both are inherited. Its constructor passes the registration and 6 wheels to the Vehicle constructor and then sets its own attribute.

    LearnWhy inheritance helps

      0 of 3

      LabWho can use an inherited member?

      Vehicle is in the package transport and declares speed with the modifier you choose. Find out which classes may use it.

      # Vehicle's constructor sets: self.__speed = 5
      class Car(Vehicle):
      def check(self):
      return self.__speed

      AttributeError: 'Car' object has no attribute '_Car__speed' (name mangling: inside Car, __speed means _Car__speed)

      Java: can each place use speed? Cells you have tried are filled in.
      JavaVehicle itselfCar: subclass, same packageGarage: not a subclass, same packageSportsCar: subclass, other packageShop: not a subclass, other package
      private
      default
      protected
      public

      Try every combination to complete the Java table (1 of 20). Switch to Python to compare its conventions.

      LearnAccess modifiers and inheritance (Java)

      ModifierThe class itselfSame packageSubclass in another packageAny other class
      privateYesNoNoNo
      default (no modifier)YesYesNoNo
      protectedYesYesYesNo
      publicYesYesYesYes

      A subclass inherits private attributes too (every Bus object has its own reg), but its own code cannot use them by name: it must go through the superclass’s public or protected methods. Python has no default level and enforces nothing except name mangling for __name.

      CodePrivate and protected in a subclass

      class Vehicle:
      def __init__(self, reg, wheels):
      self.__reg = reg
      self._wheels = wheels
      def getReg(self):
      return self.__reg
      class Trailer(Vehicle):
      def __init__(self, reg):
      super().__init__(reg, 2)
      def label(self):
      # return self.__reg # AttributeError: no attribute '_Trailer__reg'
      return self.getReg() + " (" + str(self._wheels) + " wheels)"
      print(Trailer("S-TR 7").label())
      Output
      S-TR 7 (2 wheels)

      CheckIs inheritance the right relationship?

      Should the first class inherit from the second?

      1. SavingsAccount from BankAccount
      2. Engine from Car
      3. Student from Person
      4. Library from Book
      5. ElectricCar from Car
      6. Wheel from Bicycle

      CheckQuick check

      In Java, a Bus constructor sets seats but does not call super(…), and Vehicle has only the constructor Vehicle(String reg, int wheels). What happens?

      ExamWorked exam answer

      A game has Enemy, Dragon and Goblin classes. Every enemy has health and a position and can move and take damage; dragons can also breathe fire and goblins can steal gold. Explain how inheritance would promote code reuse in this game.

      [3]
        Try writing your own answer first.

        ReviewMistakes examiners see

        Misconception

        Saying that a subclass “cannot see” private attributes and so does not have them: it has them, but must use the superclass’s methods.

        Misconception

        Using inheritance for “has a” relationships, e.g. making Engine a subclass of Car.

        Misconception

        Repeating the superclass’s attributes in the subclass instead of calling the superclass constructor.

        Exam tip

        In code answers, show extends / (Superclass) and the call to super.

        Exam practiceExam-style questions

        4 questions · 11 marks. Answer each one first, then mark it yourself against the markscheme. Your answers are saved in this browser only.

        Scenario

        A school’s staff system has an Employee class with private attributes name and salary, a constructor that sets both, and the public accessors getName() and getSalary().

        (a)Construct · AO3[4]

        Construct a Teacher class that inherits from Employee, adds a subject, and has a method timetableName() that returns the name followed by the subject in brackets, e.g. Mr Ito (Physics).

        (b)Explain · AO3[2]

        A developer suggests making name protected in Employee so that timetableName() can use the attribute directly. Explain one disadvantage of this compared with using getName().

        (c)Explain · AO3[2]

        Explain why subject should be in Teacher and not in Employee.

        (d)Explain · AO3[3]

        Later, every member of staff must have a pension contribution calculated as 5 % of their salary. Explain how the class hierarchy keeps this change small.

        0 / 11

        0 of 4 questions marked. Mark every question to see your total.

        Exam-style questions written for Praxis IB in the format of the 2027 specimen papers. They are not IB past-paper questions.