LightMySky

Inheritance and Overriding Behaviour

A class can extend another, taking its fields and methods and replacing the ones it needs to do differently. Shared behaviour is written once, and the differences sit in the class they belong to.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Write a subclass that adds one field and overrides one method
  • Predict which version of a method runs for an object of the subclass
  • Say when two classes should share a parent and when they should not

1 · Read

A subclass is a new class that borrows everything from another class, called its superclass. A SportsCar class can inherit from a general Car class, picking up wheels and an engine without rewriting them. Shared behaviour is written once, and each difference sits in the class it belongs to.

Try it together

Take class Vehicle with a method trip_info, then class Bus that extends Vehicle, adds seats, and writes its own trip_info. A Bus object calling trip_info runs the Bus version, because the subclass version replaces the parent one for its objects. That replacement is called overriding.

A subclass may use an inherited method exactly as it is when nothing needs to change. When an override still needs the old behaviour, it calls the parent version with super() and builds on top instead of throwing it away. Calling the same method name on different classes and getting each own answer is called polymorphism.

Good to know

Share a parent only when each child truly is one of the parent kind. Bus and Car both are Vehicles, so the parent earns its place. When two classes merely look alike but neither is the other, keep them separate instead of forcing a family.

Inherit what is shared, override what differs, and only join classes that truly share a kind.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Inheritance and Overriding Behaviour · Computing, ages 16 to 18 · LightMySky