08.05. Composition

Composition

  • Eclipse: Oxygen
  • Java: 1.8 

     The composition is the core concept of object-oriented programming. The composition is the design technique to implement a has-a relationship between different types of objects/classes. We can use Java inheritance or object composition in Java for code reuse.

    Difference between inheritance and composition?

    In Java, Inheritance is suitable only when classes are in a relationship. For example Car, Truck Bike are a vehicle and all these vehicles have common features of vehicle class (Superclass). But to represent the engine relationship, we have an alternative to inheritance known as composition.

    In inheritance, we can derive some functionality to a subclass of the parent class, in the composition a class reuses the functionality by creating a reference to the object of the class.

    For example, A laptop is a composite object containing other objects such as Screen, processor, Ram, Hard drive, Graphics card, Optical drive, and Keyboard. In other words, the laptop object shares a HAS-A relationship with other objects. The laptop is a composition that consists of multiple components and works together as a team to solve a problem. The following components can be simple as well as complex.

In the following list, Screen, RAM, Hard drive, and optical drive Keyboard are simple composition.

  • Screen -> Full HD/HD
  • Ram-> DDR1/DDR2/DDR3/DDR4
  • Hard drive-> 500 GB/1 TB/ 2TB
  • Optical drive-> Single layer/multilayer
  • Keyboard-> backlit/standard

Processors and graphics cards are complex components. There are multiple things involved.

Processor

  • Brand
  • Series
  • Generation
  • No of Cores
  • No of threads
  • Cache memory
  • Frequency

Graphics card

  • Brand
  • Series
  • Memory

Composition setting up

In inheritance, we deal with the attributes of other classes. Composition studies have a relationship in which we ‘inherit’ or use objects from other classes.

In the following example, Laptop HAS-A Processor may have many features. Therefore, we inherit the object and then access the attributes through these objects.

Output

Working with composition

As we discussed, the classes inherit the objects of other classes. Hence to access the attributes we need to create the getters to return the object of the classes by the virtue of which we can access the required attribute.

Output

intel

Importance:

  • By using composition, we can control the visibility of another object for customer classes and reuse only what we need.
  • The composition allows the creation of backend classes when necessary.

Contributed by: Salim Sheikh

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
c c
c c
3 years ago

a lot of errors in this page.