Methods to Differentiate Between Inheritance and Composition in Object-Oriented Programming

Tuanh.netTuanh.net
2 min read

1. What is Inheritance in OOP?

Inheritance is a mechanism where a new class (subclass) inherits properties and behaviors (methods) from an existing class (superclass). This relationship is often described as an "is-a" relationship. For example, a Car is a type of Vehicle, meaning that Car can inherit common properties and behaviors from the Vehicle class.

1.1 How Does Inheritance Work?

In Java, inheritance is implemented using the extends keyword. The subclass inherits all non-private fields and methods from the superclass, allowing for code reuse and logical hierarchies.

Example:

class Vehicle {
String brand;
int speed;

void accelerate() {
speed += 10;
}
}

class Car extends Vehicle {
int numberOfDoors;

void displayInfo() {
System.out.println("Brand: " + brand + ", Speed: " + speed + ", Doors: " + numberOfDoors);
}
}

In this example, Car inherits brand and speed fields, as well as the accelerate() method from the Vehicle class.

1.2 Advantages of Inheritance

  • Code Reusability: Common functionalities can be written once in the superclass and reused by multiple subclasses.
  • Logical Hierarchy: Helps create a natural hierarchy that models real-world relationships.

1.3 Disadvantages of Inheritance

  • Tight Coupling: Subclasses are tightly coupled with their superclasses, making the code harder to modify and extend.
  • Fragile Base Class Problem: Changes in the superclass may unintentionally affect the behavior of subclasses.

2. What is Composition in OOP?

Composition involves building complex types by combining objects of other types, typically through class fields. It is often described as a "has-a" relationship. For example, a Car has an Engine, meaning that the Car class will have an instance of the Engine class.

2.1 How Does Composition Work?

In composition, a class is composed of one or more objects of other classes, rather than inheriting from them. This promotes flexibility and reduces dependency between classes.

Read more at : Methods to Differentiate Between Inheritance and Composition in Object-Oriented Programming

0
Subscribe to my newsletter

Read articles from Tuanh.net directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tuanh.net
Tuanh.net