- An "is-a" relationship represents inheritance or specialization, where
one class is a subtype of another.
- It implies that an object of the derived class is also an object of
the base class.
- In JavaScript, this is achieved through prototype-based inheritance or
class-based inheritance.
- A "has-a" relationship represents composition or aggregation, where
one class has another class as a part or member.
- It implies that an object of one class contains an object of another
class.
// Base class representing a Vehicle
class Vehicle {
drive() {
console.log(`Vehicle is moving.`);
}
}
// Engine class representing a part of a Vehicle
class Engine {
start() {
console.log("Engine started.");
}
}
// Maruti class representing a specific type of Vehicle (is-a relationship with Vehicle)
class Maruti extends Vehicle {
constructor() {
super(); // Call the constructor of the base class (Vehicle)
// Engine as a part of Maruti (has-a relationship with Engine)
this.engine = new Engine();
}
honk() {
console.log(`Maruti is honking.`);
}
}
// Creating objects
const myMaruti = new Maruti();
myMaruti.drive(); // Inherited from Vehicle
myMaruti.honk(); // Specific to Maruti
myMaruti.engine.start(); // Part of Maruti
- Vehicle represents a generic vehicle and serves as
the base class.
- Engine is a separate class representing a part of a
vehicle (has-a relationship).
- Maruti is a specific type of vehicle (is-a
relationship with Vehicle) and contains an
Engine as a part (has-a relationship with
Engine).
This structure better reflects the "is-a" and "has-a" relationships
between the classes.