Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Composition: Has-A vs Is-A

A laptop is a computer, so Laptop extends Computer. A computer has a CPU, so the Cpu goes inside as a field. Nora's PC hands Excel to its Core i5, Omar's PC swaps a Core i3 for a Ryzen 9, and one Computer class serves any CPU.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Decide between extends and composition by saying 'is a' or 'has a' aloud
  • Hold a part object in a field and delegate work to it
  • Swap a part at run time without changing the whole
  • Combine is-a and has-a in one class

Before you start

  • Java inheritance: extends and super
  • Java polymorphism

Inheritance isn't the only way to build classes from other classes. Composition keeps one object inside another. How do you choose? Say the sentence out loud.

  • "A laptop is a computer." True. So Laptop extends Computer: an is-a relationship, inheritance.
  • "A computer is a CPU." No. "A computer has a CPU." True. So the CPU goes inside the computer as a field: a has-a relationship, composition.
Is-a: Laptop has a line up to Computer, meaning extends. Has-a: inside the Computer box sits a Cpu box, meaning composition. Main calls start("Excel") on the Computer, which hands the task inward to cpu.run, and the answer "Core i5 runs Excel" comes back out. Computer Laptop is-a (extends) Computer (Nora) start("Excel") hands it inward Cpu: Core i5 run(task) has-a (a field)
A line upward means extends; a box inside a box means composition.

A part and a whole

package org.studyeasy.s03l13;

public class Cpu {
    private String model;

    public Cpu(String model) {
        this.model = model;
    }

    // The Cpu does the work and hands back a sentence
    public String run(String task) {
        return model + " runs " + task;
    }
}
package org.studyeasy.s03l13;

public class Computer {
    private String owner;
    private Cpu cpu;                // HAS-A: a Computer has a Cpu

    public Computer(String owner, Cpu cpu) {
        this.owner = owner;
        this.cpu = cpu;
    }

    public void start(String task) {
        // delegation: the Cpu does the real work
        System.out.println(owner + "'s PC: " + cpu.run(task));
    }

    public void swapCpu(Cpu newCpu) {
        this.cpu = newCpu;          // new Cpu, same Computer
    }
}

The cpu field holds a whole object. The constructor receives it, so whoever builds the computer picks its CPU. start doesn't run the task itself; it hands it inward to cpu.run and prints what comes back. Handing work to an inner object like this is called delegation.

Put a Cpu inside a Computer

package org.studyeasy.s03l13;

public class Ex01_BuildAPc {
    public static void main(String[] args) {
        Cpu i5 = new Cpu("Core i5");                 // the part
        Computer office = new Computer("Nora", i5);  // the whole
        office.start("Excel");
        office.start("Zoom");
    }
}
Nora's PC: Core i5 runs Excel
Nora's PC: Core i5 runs Zoom

Build the part, then the whole, then call. Pass null instead of a Cpu and start throws a NullPointerException: there's no part inside to do the work.

Same Computer, new Cpu

package org.studyeasy.s03l13;

public class Ex02_SwapParts {
    public static void main(String[] args) {
        Computer studio = new Computer("Omar", new Cpu("Core i3"));
        studio.start("Video export");
        studio.swapCpu(new Cpu("Ryzen 9"));   // same PC, new Cpu
        studio.start("Video export");         // same call
    }
}
Omar's PC: Core i3 runs Video export
Omar's PC: Ryzen 9 runs Video export

This is where composition shines. The computer object stays the same; only the part inside changes, so the same call gives a new answer. With inheritance you couldn't do that: an object's class is fixed when it's created. And class Computer extends Cpu would be wrong anyway: a computer isn't a CPU.

One class, any Cpu

package org.studyeasy.s03l13;

public class Ex03_MixAndMatch {
    public static void main(String[] args) {
        // One Computer class, any Cpu, zero subclasses
        Computer[] lab = {
            new Computer("Nora", new Cpu("Core i3")),
            new Computer("Omar", new Cpu("Core i5")),
            new Computer("Mira", new Cpu("Ryzen 9"))
        };
        for (Computer pc : lab) {
            pc.start("Build report");
        }
    }
}
Nora's PC: Core i3 runs Build report
Omar's PC: Core i5 runs Build report
Mira's PC: Ryzen 9 runs Build report

The alternative would be a subclass per CPU (IntelComputer, AmdComputer, ...), and it would multiply with every new model. With composition the CPU is a choice you pass in, not a subclass.

A Laptop is a Computer, and has a Cpu

package org.studyeasy.s03l13;

public class Laptop extends Computer {      // IS-A: a Laptop is a Computer
    public Laptop(String owner, Cpu cpu) {
        super(owner, cpu);
    }

    public void closeLid() {
        System.out.println("Lid closed");
    }
}
Laptop travel = new Laptop("Mira", new Cpu("Core i7"));
travel.start("Notes");     // inherited from Computer: a Laptop IS-A Computer
travel.closeLid();         // only a Laptop has this
Mira's PC: Core i7 runs Notes
Lid closed

super(owner, cpu) hands both values up, because the fields are private to Computer. start is inherited, and the CPU still does the work, so one class uses both relationships. A plain Computer has no closeLid().

Recap

SentenceRelationshipCode
A laptop is a computeris-aclass Laptop extends Computer
A computer has a CPUhas-aprivate Cpu cpu;
A computer is a CPU?falsedon't extend
Change a part laterhas-astudio.swapCpu(...)
Many CPU choiceshas-aone class, many objects

When one thing is a kind of another, extend it. When one thing is made of another, keep it as an object inside and let it do the work.

Keep going in Java · 35 of 79

Previous
Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
Next post
Java Abstract Classes: A Parent That Leaves One Blank
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • A part and a whole
  • Put a Cpu inside a Computer
  • Same Computer, new Cpu
  • One class, any Cpu
  • A Laptop is a Computer, and has a Cpu
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.