Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 12

IS-A and HAS-A

Two ways to connect classes — and a test that tells them apart

22m55 XP
→→→

What you'll be able to do

  • Apply the IS-A / HAS-A test to any pair of classes
  • Build a HAS-A relationship by holding another object as a field
  • Delegate work to a contained object instead of inheriting it
  • Recognise the three flavours of HAS-A you will meet in Java code
1

IS-A vs HAS-A

The question that decides your design

Every time two classes must work together you face one question: is this a *kind of* that, or does this *have* one of those?

There are exactly two ways for classes to relate: - IS-A — inheritance. class Dog extends Animal. A Dog *is a kind of* Animal, so it inherits everything Animal has. - HAS-A — the object holds another object as a field. class Car { private Engine engine; }. A Car *contains* an Engine; it is not a kind of engine. The test is a sentence you say out loud: | Sentence | Verdict | | --- | --- | | 'A Dog is an Animal' ✓ | IS-A → extends | | 'A Car has an Engine' ✓ | HAS-A → field | | 'A Car is an Engine' ✗ | never inherit | | 'A Student has an Address' ✓ | HAS-A → field | If both sentences sound acceptable, choose HAS-A. It is the looser, safer, more flexible relationship — the reason for the famous advice you will meet at the end of this module.

`Dog extends Animal` vs `Dog has an Animal`

IS-A (inheritance)

Dog extends Animal

Main.java
1class Dog extends Animal {
2 // inherits name, eat(), sleep()
3}
  • A Dog can be used wherever an Animal is expected
  • Inherits the parent's members automatically
  • Locked in at compile time; one parent only
  • Correct here: a dog really is an animal

HAS-A (composition)

Dog has an Animal

Main.java
1class Dog {
2 private Animal animal; // a dog that contains an animal?
3}
  • A Dog is *not* usable as an Animal
  • Must forward every call manually
  • Can be swapped at run time
  • Wrong here — but exactly right for Car/Engine

The three flavours of HAS-A

RelationshipMeaningLifetimeExample
Associationtwo objects simply know each otherfully independentStudent ↔ Teacher
Aggregationwhole–part, but the part can live aloneindependentTeam has Players
Compositionwhole–part, the part cannot live alonedies with the wholeHouse has Rooms

All three are HAS-A; they differ only in how tightly the lifetimes are bound. Lesson 2 makes the distinction concrete in code.

2

Composition

Composition: build a class out of other classes

A Car does not reimplement combustion. It holds an Engine and asks it to start.

Composition is HAS-A implemented with a field, plus delegation: the outer object exposes a method and forwards the real work to the object it holds. ``java class Car { private Engine engine; // the HAS-A void start() { engine.start(); // the delegation } } ` Three properties make this powerful: 1. **Encapsulation survives** — Car uses only Engine's public methods, so Engine can change internally without touching Car`. 2. Combinable — a class may hold as many collaborators as it needs. There is no 'one parent' limit. 3. Replaceable at run time — if the field is typed by an interface, you can swap the collaborator while the program is running; inheritance is fixed at compile time.

A company hires specialists

A company does not *become* an accountant to file its taxes — it employs one and forwards the task. If the accountant leaves, the company hires another and keeps working exactly the same way. Inheritance is 'become the thing'; composition is 'employ the thing'.

Anatomy of a composed class

Main.java
1class Car {
2 private String brand;
3 private Engine engine;
4
5 Car(String brand, int horsepower) {
6 this.brand = brand;
7 this.engine = new Engine(horsepower);
8 }
9
10 void start() {
11 System.out.println(brand + " is starting...");
12 engine.start();
13 }
14}
private Engine engine;
The HAS-A relationship in one line: a field whose type is another class. private keeps the engine hidden from outsiders.
this.engine = new Engine(horsepower);
The Car creates and owns its Engine — the tightest form, true composition. If the Engine were passed in as a parameter instead, it would be aggregation.
engine.start();
Delegation. Car does not know how an engine works; it forwards the request. Change Engine's internals and this line still compiles.
Car HAS-A Engine

Add a `FuelTank` class with `refuel()` and give Car a second collaborator. Notice you can hold as many as you like — no 'one parent' limit.

Output
Press Run to execute this example.

You have been composing since Module 2

Any field whose type is another class is a HAS-A relationship — Student with an Address, AlertService with a Notifier, Cart with a Discountable. Composition is not an advanced technique; it is the most common relationship in real code.

Prove it — coding challenges

Common mistakes

Wrongclass Car extends Engine
WhyA car is not a kind of engine — the IS-A sentence is false, and Car would inherit engine internals it should not expose.
FixGive Car an `Engine` field and delegate.
WrongInheriting just to reuse two convenient methods.
WhyYou also inherit everything else, including future changes to the parent — and you use up your single `extends` slot.
FixHold an instance of the helper class and call the two methods you need.
WrongExposing the contained object with a public getter (`car.getEngine().stop();`).
WhyCallers reach past the wrapper and its encapsulation is gone.
FixExpose intent-revealing methods (`car.stop()`) and keep the collaborator private.

Lesson playground

Free practice

Student HAS-A Address. Add a `University` class that a Student also has, and print all three pieces of information from one method.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

A composed object delegating to its part. What is printed?

Main.java
1class Printer {
2 void print(String text) {
3 System.out.println("[printed] " + text);
4 }
5}
6
7class Office {
8 private Printer printer;
9
10 Office() {
11 this.printer = new Printer();
12 }
13
14 void printReport(String title) {
15 System.out.println("Preparing " + title);
16 printer.print(title);
17 }
18}
19
20public class Main {
21 public static void main(String[] args) {
22 Office office = new Office();
23 office.printReport("Q3 report");
24 }
25}

Summary

  • Two relationships exist: IS-A (`extends`) and HAS-A (a field of another class type).
  • Say the sentence out loud; if both sound acceptable, prefer HAS-A.
  • Composition = hold a collaborator privately and delegate work to it.
  • HAS-A comes in three strengths: association, aggregation and composition.