VOOZH about

URL: https://www.geeksforgeeks.org/java/favoring-composition-over-inheritance-in-java-with-examples/

⇱ Favoring Composition Over Inheritance In Java With Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Favoring Composition Over Inheritance In Java With Examples

Last Updated : 17 Mar, 2025

In object-oriented programming (OOP), choosing between inheritance and composition is crucial for designing flexible and maintainable code. This article explores why you should favor composition over inheritance, with simple explanations and examples.

What is Inheritance?

Inheritance is when a new class is based on an existing class. The new class (subclass) inherits properties and methods from the existing class (superclass). This relationship is known as "is-a." For example, an Employee "is a" Person because it inherits from the Person class.

Example:


Output
Name: Geek1
Age: 30
Salary: 50000

In this example, the Employee class inherits from Person and adds a new property, salary.

What is Composition?

Composition involves creating classes that include instances of other classes. This is known as a "has-a" relationship. For example, a Person "has an" Address because it contains an Address object.

Example:


Output
Name: Geek1
Address: 123 Main St, Springfield, 12345

In this example, the Person class uses composition to include an Address object. This creates a "has-a" relationship between Person and Address.

Why Favor Composition Over Inheritance?

  • Flexibility: With composition, you can easily change or replace components (like Address) without affecting the Person class.
  • Encapsulation: Composition keeps the details of the composed class (like Address) hidden from the outside, making your code more secure and easier to manage.
  • Avoid Fragile Base Class Problem: Changes in a superclass can break subclasses. Composition reduces this risk because changes in one class do not directly impact others.
  • Better Testability: Composition makes it easier to test individual components by substituting mock objects if needed.

Conclusion

Favoring composition over inheritance is a best practice in OOP that leads to more flexible, maintainable, and testable code. By using composition, you create "has-a" relationships that are often more adaptable and less prone to problems than "is-a" relationships from inheritance.

Comment