Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 6

extends: a child class

Animal → Dog / Cat, and the IS-A test that keeps you honest

22m55 XP
→→→

What you'll be able to do

  • Use `extends` to put shared state and behaviour in a parent class
  • Say exactly which members a subclass inherits and which it does not
  • Apply the IS-A test to decide whether inheritance is the right tool
  • Distinguish `Dog extends Animal` from `Dog has an Animal`
1

Inheritance

One parent, many children

Three classes need `name`, `eat()` and `sleep()`. Copy them three times — or write them once and say 'Dog IS-A Animal'.

Suppose you write Dog, Cat and Bird. All three have a name, all three eat and sleep. Copy-pasting those members into each class means three places to fix every bug and three places to add every feature. Inheritance lets one class take everything another class has and then add its own extras. The keyword is extends: - The class you inherit from is the parent (also: superclass, base class). - The class that inherits is the child (also: subclass, derived class). The relationship it expresses is IS-A: a Dog *is a* Animal. That sentence is not decoration — it is the test that tells you whether inheritance is appropriate at all.

The base blueprint and the special editions

A car factory has one base blueprint: chassis, engine mount, four wheels, steering. The 'Taxi' edition takes the entire base blueprint and adds a meter and a roof sign. The 'Police' edition takes the same base and adds a siren. Nobody redraws the chassis. Change the base blueprint and every edition inherits the change — that is extends.

Animal → Dog / Cat

Main.java
1class Animal {
2 protected String name;
3
4 void setName(String name) {
5 this.name = name;
6 }
7
8 void eat() {
9 System.out.println(name + " is eating");
10 }
11}
12
13class Dog extends Animal {
14 void bark() {
15 System.out.println(name + " says Woof");
16 }
17}
protected String name;
protected so subclasses may use it directly (Module 5). Had it been private, Dog would need getName() instead.
void eat() {
Written once, in the parent. Every present and future subclass gets it for free.
class Dog extends Animal {
The whole mechanism in one line: Dog now has name, setName and eat without repeating them, and can add more.
void bark() {
Dog-specific behaviour. It reads the inherited name as if it were declared here — because, from Dog's point of view, it is.
Two children, one parent

Add a `Bird extends Animal` with a `fly()` method, then make a Bird eat and fly. Notice you write no `eat()` at all.

Output
Press Run to execute this example.

Java has single inheritance — and one hidden ancestor

A class may extend exactly one class: class A extends B, C does not compile. (Multiple *interfaces* are allowed — Module 11.) And every class you write already extends Object implicitly, which is where toString() and equals() come from.

Prove it — coding challenges

2

Inherited Fields

What is inherited — and what never is

Inheritance checklist

Member of the parentInherited?Notes
public / protected fields✅usable directly inside the subclass
package-private fields✅ same package onlyinvisible to a subclass in another package
private fields⚠️ exist, not accessiblethe object still contains them; the subclass must use public/protected methods
public / protected methods✅can be used as-is or overridden (Module 7)
private methods❌not visible, cannot be overridden
constructors❌ neverbut the child *calls* one with super(...) — next lesson
static members✅ accessiblethey belong to the class, not the object
A private parent field is present but locked
Main.java
1class Account {
2 private double balance; // exists in every subclass object...
3 public double getBalance() { return balance; }
4}
5
6class Savings extends Account {
7 void show() {
8 // System.out.println(balance); // error: balance has private access
9 System.out.println(getBalance()); // ...but reachable through the inherited method
10 }
11}
This is why parents expose `protected` or `public` accessors: the subclass needs a legal door to the state it inherited.
3

IS-A vs HAS-A

IS-A vs HAS-A: `Dog extends Animal` or `Dog has an Animal`?

Both compile. Only one describes reality — and choosing wrong is the most expensive mistake in OOP design.

The same two classes, two relationships

IS-A — inheritance

Dog extends Animal

Main.java
1class Dog extends Animal {
2 void bark() { }
3}
4
5Dog d = new Dog();
6d.eat(); // inherited
7Animal a = d; // a Dog IS-A Animal
  • Dog *is a kind of* Animal
  • Dog can be used anywhere an Animal is expected
  • Dog gets Animal's members automatically
  • Right when the child is a specialisation

HAS-A — composition

Dog has an Animal (as a field)

Main.java
1class Dog {
2 private Animal animal; // a part, not a parent
3
4 void bark() { }
5}
6
7Dog d = new Dog();
8// d.eat(); // does NOT exist
9// Animal a = d; // NOT allowed
  • Dog *contains* an Animal — nonsense for animals
  • No inherited members, no substitutability
  • Perfect for Car has an Engine (Module 12)
  • Right when the child owns a part

The two-question test before you type `extends`

  1. Say the sentence out loud: 'A Car IS-A Vehicle' ✅. 'A Car IS-A Engine' ❌ → that one is HAS-A.
  2. Then the substitution test: can the child be handed to *every* method that accepts the parent, without surprising it? If a Penguin extends Bird would break bird.fly(), your hierarchy is wrong.
  3. If both answers are not clearly yes, use composition — a field — instead.

Inheritance is for *what a thing is*, not for code reuse alone

Extending a class only because it happens to contain a method you want is the classic beginner trap (class InvoicePrinter extends ArrayList). You inherit its entire public API — and its future changes. Module 12 turns this into a design rule: favour composition over inheritance.

Common mistakes

Wrongclass Car extends Engine { }
WhyA car is not a kind of engine — it *has* one. The IS-A sentence fails.
Fixclass Car { private Engine engine; } — composition.
WrongReading a parent's private field from the subclass.
Why`private` never crosses the class boundary, even for children.
FixUse the inherited getter, or make the field `protected` if children truly need it.
Wrongclass A extends B, C { }
WhyJava allows only one superclass.
FixExtend one class and implement as many interfaces as you like (Module 11).

Lesson playground

Free practice

A Vehicle parent with two children. Add a `Truck extends Vehicle` with 6 wheels and a `load()` method — you should not need to rewrite `start()` or `info()`.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 4

Circle declares no label and no describe(). What is printed?

Main.java
1class Shape {
2 String label = "shape";
3
4 void describe() {
5 System.out.println("I am a " + label);
6 }
7}
8
9class Circle extends Shape {
10 double radius = 2;
11
12 void area() {
13 System.out.println("Area: " + (3.14 * radius * radius));
14 }
15}
16
17public class Main {
18 public static void main(String[] args) {
19 Circle c = new Circle();
20 c.describe();
21 c.area();
22 System.out.println(c.label);
23 }
24}

Summary

  • `class Child extends Parent` gives the child every accessible member of the parent, written once.
  • Private members exist in the subclass object but are only reachable through inherited methods; constructors are never inherited.
  • Java allows a single superclass, and every class silently extends `Object`.
  • Use inheritance only when the IS-A sentence and the substitution test both hold — otherwise use a field (HAS-A).