>> ZG·Lingua >  >> Language Resources and Tools >> Corpus Resources

Can you give me an example of composition?

Example of Composition

Imagine you're making a delicious fruit salad.

Here's how composition works in this context:

Ingredients:

* Fruit: This is like the individual classes in object-oriented programming. Each fruit has its own unique properties (color, taste, texture) and behaviors (can be sliced, can be eaten).

* Salad Bowl: This is like the main class in object-oriented programming. It acts as a container for all the fruits, bringing them together to form a complete dish.

Composition:

* The salad bowl doesn't "have a" fruit. It "has a collection of" fruits. Each fruit exists independently, but they come together within the context of the salad bowl.

* The salad bowl doesn't inherit properties from the fruits. It simply holds them and defines how they interact within the salad.

* The salad bowl can add or remove fruits as needed, giving it flexibility in its composition.

Example:

* Fruit: Apple, Banana, Strawberry

* Salad Bowl: This salad bowl holds apples, bananas, and strawberries. It also defines the way these fruits are sliced and arranged.

In Code:

```java

class Fruit {

String color;

String taste;

}

class Apple extends Fruit {

// specific apple properties

}

class Banana extends Fruit {

// specific banana properties

}

class SaladBowl {

List fruits;

void addFruit(Fruit fruit) {

fruits.add(fruit);

}

void prepareSalad() {

// slicing and arranging fruits

}

}

// Example Usage

SaladBowl mySalad = new SaladBowl();

mySalad.addFruit(new Apple());

mySalad.addFruit(new Banana());

mySalad.prepareSalad();

```

This demonstrates composition:

* The `SaladBowl` class doesn't inherit from `Fruit` or its subclasses. It composes them by holding them in a list.

* The `SaladBowl` class has its own unique behavior (preparing the salad) that involves the fruits it holds.

In contrast, inheritance would mean:

* The `SaladBowl` class inherits properties and methods from the `Fruit` class, making it a type of fruit. This would be illogical and inappropriate.

Composition allows for flexible and reusable code, as you can easily create different salad bowls with varying combinations of fruits.

Copyright © www.zgghmh.com ZG·Lingua All rights reserved.