Sobes.tech
Junior

What do you know about class composition in programming?

sobes.tech AI

Answer from AI

Composition is a "contains" or "part-whole" relationship where one class (composite) contains a reference to another class (component) or its instances. The lifecycle of the component is usually closely tied to the lifecycle of the composite. This is a strong relationship where the component cannot exist without the composite.

Advantages of composition:

  • Flexibility: Easier to change behavior by changing components.
  • Reduced coupling: Classes depend less on each other compared to inheritance.
  • Reusability: The same components can be used in different composites.

Example: The Car class can contain a reference to the Engine class. If the Car is destroyed, the Engine (in this context) also ceases to exist.

class Engine {
    // engine properties and methods
}

class Car {
    private Engine engine; // composition

    public Car() {
        this.engine = new Engine(); // creating a component inside the composite
    }

    // other properties and methods of the car
}

Difference from aggregation: In aggregation, components can exist independently of the composite (weak relationship). Example: The University class contains references to instances of the Student class. Students can exist outside the university.

In Android development, composition is actively used, for example, when creating views (ViewGroup contains View), working with dependencies via Dagger/Hilt. This is the preferred approach compared to multiple inheritance (which is not available in Java/Kotlin for classes) and is often more flexible than single inheritance.

class UserRepository(private val apiService: ApiService) {
    // UserRepository "uses" ApiService (composition/aggregation)
    fun fetchUser(userId: String) {
        // apiService.getUser(userId)
    }
}
What do you know about class composition in… - sobes.tech