Menu
Coddy logo textTech

The "has-a" vs. "is-a"

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 47 of 56.

In object-oriented programming, there are two main types of relationships between objects: "has-a" (composition) and "is-a" (inheritance). While inheritance creates parent-child hierarchies, composition builds objects by combining smaller, focused components.

Let's first understand the "is-a" relationship through inheritance:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  eat() {
    console.log(`${this.name} is eating.`);
  }
}

// Dog "is-a" Animal - inheritance relationship
class Dog extends Animal {
  bark() {
    console.log(`${this.name} says woof!`);
  }
}

Now let's look at the "has-a" relationship through composition:

class Engine {
  start() {
    console.log("Engine started");
  }
}

// Car "has-a" Engine - composition relationship
class Car {
  constructor() {
    this.engine = new Engine(); // Composition
  }
  
  startCar() {
    this.engine.start();
    console.log("Car is running");
  }
}

The key difference:

  • "is-a" (inheritance): A Dog IS AN Animal
  • "has-a" (composition): A Car HAS AN Engine
challenge icon

Challenge

You're given the component classes (Processor, Memory) and most of the Computer class. Your task is to complete the constructor in the computer.js file:

  1. Create a processor property using the Processor class
  2. Create a memory property using the Memory class
  3. Pass processorSpeed to the Processor constructor and memorySize to the Memory constructor

Cheat sheet

In object-oriented programming, there are two main types of relationships between objects:

  • "is-a" relationship (inheritance): Creates parent-child hierarchies where a subclass extends a parent class
  • "has-a" relationship (composition): Builds objects by combining smaller, focused components

Inheritance example ("is-a"):

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  eat() {
    console.log(`${this.name} is eating.`);
  }
}

// Dog "is-a" Animal
class Dog extends Animal {
  bark() {
    console.log(`${this.name} says woof!`);
  }
}

Composition example ("has-a"):

class Engine {
  start() {
    console.log("Engine started");
  }
}

// Car "has-a" Engine
class Car {
  constructor() {
    this.engine = new Engine(); // Composition
  }
  
  startCar() {
    this.engine.start();
    console.log("Car is running");
  }
}

Try it yourself

import { Computer } from './computer.js';

const myComputer = new Computer(3.5, 16);
myComputer.start();
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming