Aggregation is another relationship between classes in object-oriented programming. In aggregation, one class contains an object of another class, but the contained object can exist independently of the class that contains it. Aggregation represents a "has-a" relationship, where one class has another class as a part.
In Java, aggregation is typically implemented by creating a member variable in one class that refers to an object of another class. The object can be created, modified, and destroyed independently of the containing class. The "aggregated" class is not a part of the "container" class in the same way that subclasses are part of their superclasses in inheritance.
Here's a simple example to illustrate aggregation:
// Aggregated classclass Engine {private String type;public Engine(String type) {this.type = type;}public String getType() {return type;}}// Container class using aggregationclass Car {private String model;private Engine engine; // Aggregation: Car has an Enginepublic Car(String model, Engine engine) {this.model = model;this.engine = engine;}public String getModel() {return model;}public Engine getEngine() {return engine;}}public class AggregationExample {public static void main(String[] args) {// Creating an instance of the aggregated class (Engine)Engine carEngine = new Engine("V6");// Creating an instance of the container class (Car) with the aggregated classCar myCar = new Car("Sedan", carEngine);// Accessing properties using aggregationSystem.out.println("Car Model: " + myCar.getModel());System.out.println("Engine Type: " + myCar.getEngine().getType());}}
Комментариев нет:
Отправить комментарий