Free degree-level programming lessons for careful independent study.

Degree Level Programmes · Programming 2 · Lesson 5

Inheritance for Reuse

Use inheritance carefully as one form of reuse, while recognising when composition is easier to maintain.

Lesson Overview

Use inheritance carefully as one form of reuse, while recognising when composition is easier to maintain.

Portfolio focus: Create a base class and one subclass.

ConceptObject-oriented reuse
Run fileInheritanceForReuseDemo.java
BaselineAda has 20 credits
Evidence3 tasks

Starter: think before typing

Before running this object-oriented reuse example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Ada has 20 credits`; predict how the focus line helps produce that evidence.

Learning Objectives

  • Write a simple subclass.
  • Explain the is-a relationship.
  • Identify inherited behaviour.
  • Compare inheritance with composition for maintainability.

Learning Outcomes

  • By the end of the lesson, you can write a simple subclass.
  • By the end of the lesson, you can explain the is-a relationship.
  • By the end of the lesson, you can identify inherited behaviour.
  • By the end of the lesson, you can compare inheritance with composition for maintainability.

Why this idea exists

Inheritance exists to express a specialised kind of relationship: one type can be treated as a more specific version of another type while reusing or extending shared behaviour.

Object-oriented languages popularised inheritance as a way to model taxonomies and reuse code, but experience showed that deep inheritance trees can become rigid and surprising.

This lesson fits the arc after encapsulation because it tests design judgement. Learners should understand inheritance, but also recognise when composition, interfaces or simple delegation make the program easier to maintain.

Deep dive

Mechanism in this example

The important mechanism is visible around `StudentAccount account = new StudentAccount("Ada");`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.

Design pressure

This lesson fits the arc after encapsulation because it tests design judgement. Learners should understand inheritance, but also recognise when composition, interfaces or simple delegation make the program easier to maintain.

Failure mode to watch

For Inheritance for Reuse, deliberately disturb the assumption behind `StudentAccount account = new StudentAccount("Ada");`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the object-oriented reuse design.

Extension step

Extend the example by doing this: List what the subclass inherits. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.

Portfolio standard

The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: write one reason composition might be better than inheritance.

Lesson visual

A class hierarchy with a base Account and specialised StudentAccount, with a warning note about reuse not being free.
A class hierarchy with a base Account and specialised StudentAccount, with a warning note about reuse not being free.Download visual

Type this and run it

Create InheritanceForReuseDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.

public class InheritanceForReuseDemo {
  public static void main(String[] args) {
    StudentAccount account = new StudentAccount("Ada");
    account.deposit(20);
    System.out.println(account.summary());
  }
}

class Account {
  private final String owner;
  private int balance;

  Account(String owner) {
    this.owner = owner;
  }

  void deposit(int amount) {
    balance = balance + amount;
  }

  String summary() {
    return owner + " has " + balance + " credits";
  }
}

class StudentAccount extends Account {
  StudentAccount(String owner) {
    super(owner);
  }
}

Build and run it with:

javac InheritanceForReuseDemo.java && java InheritanceForReuseDemo

Expected baseline: Ada has 20 credits

Run the code in your browser

Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates object-oriented reuse and compare the new behaviour with the reference output.

Line-by-line explanation

Read the code as a sequence of responsibilities. The focus line for this lesson is StudentAccount account = new StudentAccount("Ada");; the surrounding lines prepare it, use its result or make the behaviour observable.

public class InheritanceForReuseDemo {

This names the runnable class for the Inheritance for Reuse example, giving the compiler and JVM one clear unit to build.

public static void main(String[] args) {

This is the program entry point. In Inheritance for Reuse, it keeps the demonstration of object-oriented reuse in one traceable starting script.

StudentAccount account = new StudentAccount("Ada");

This constructs an object for the Inheritance for Reuse example, asking Java for a value with a specific type and behaviour.

account.deposit(20);

This calls account.deposit with 20 in Inheritance for Reuse. Look for the method definition to see what work actually happens.

System.out.println(account.summary());

This prints account.summary() as the observable evidence for Inheritance for Reuse. The output lets the learner check whether the object-oriented reuse idea behaved as predicted.

}

This closes the innermost Inheritance for Reuse block, so the immediately preceding method, branch or loop has finished.

}

This closes the outer Inheritance for Reuse structure, returning the reader to the surrounding class or file.

class Account {

This starts a supporting class so Inheritance for Reuse can separate the lesson idea into its own named responsibility.

private final String owner;

This declares owner as object state for the Inheritance for Reuse design without exposing it directly. Later constructors or methods should give it a controlled value.

private int balance;

This declares balance as object state for the Inheritance for Reuse design without exposing it directly. Later constructors or methods should give it a controlled value.

Account(String owner) {

This constructor prepares a new object so the Inheritance for Reuse example can use it in a valid state.

this.owner = owner;

This assignment changes owner in Inheritance for Reuse to owner. Trace where that new value is used next.

}

This closing brace number 3 completes another layer of the Inheritance for Reuse source structure Java has been checking.

void deposit(int amount) {

This starts deposit, a named Inheritance for Reuse operation. Its parameters describe what information comes in; its body decides what work is done.

balance = balance + amount;

This assignment changes balance in Inheritance for Reuse to balance + amount. Trace where that new value is used next.

}

This closing brace number 4 completes another layer of the Inheritance for Reuse source structure Java has been checking.

Worked example

From code to explanation

Problem: Use Inheritance for Reuse to complete a small portfolio-quality step: Create a base class and one subclass.

Method: Locate the line `StudentAccount account = new StudentAccount("Ada");`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.

Reveal worked answer

The checked run should produce `Ada has 20 credits`. A strong answer links the result back to object-oriented reuse: what was created, selected, stored, called or protected, and why that matters for the portfolio task.

Trace the program

Before: Before the key operation, identify the relevant value, object, branch or resource that the object-oriented reuse concept depends on.

During: Trace `StudentAccount account = new StudentAccount("Ada");` as the Inheritance for Reuse example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.

After: Compare the run with the expected evidence: `Ada has 20 credits`.

Change: Now list what the subclass inherits, run again, and explain the smallest reason the behaviour changed.

Common misconception

A common mistake in inheritance for reuse is treating the example as a finished answer. For object-oriented reuse, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?

Quick checks

1. In this Inheritance for Reuse example, what is the best reason to focus on `StudentAccount account = new StudentAccount("Ada");`?

2. Which evidence is strongest after you edit and rerun this example?

How to study this lesson

For Inheritance for Reuse, predict how object-oriented reuse changes the run before you press Run.

Use the first portfolio task as your main edit: Create a base class and one subclass.

Use the second task as your variation: List what the subclass inherits.

Finish with evidence, not a diary entry: Write one reason composition might be better than inheritance.

Portfolio Practice

  1. Create a base class and one subclass.
  2. List what the subclass inherits.
  3. Write one reason composition might be better than inheritance.

Final self-check

Can you explain the key operation?

Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Ada has 20 credits appears.

Can you justify the portfolio evidence?

Your evidence should include the original run, one edited run, and a short note explaining how the edit affected object-oriented reuse.

Study route

Practise object-oriented reuse by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.

Next, move into Controlled Boundary Breaking and carry forward one improvement from this lesson into the next program.