The difference between inheritance, composition and aggregation

Definition of Inheritance, Composition, Aggregation

Inheritance, composition, and aggregation are three commonly used mechanisms for implementing relationships between classes in object-oriented programming.

Inheritance means that a class inherits its attributes and methods from another class. The inherited class is called parent class, base class or super class, and the inherited class is called subclass, derived class or derived classes. A subclass can inherit all the properties and methods of the parent class, rewrite or add its own properties and methods, and can continue to be inherited by other classes. Inheritance implements the "is-a" relationship, where one class is a special type of another class. For example, the Animal class can be used as a base class, and the Fish class and the Bird class can inherit the Animal class respectively, and they all inherit the properties and methods of the Animal class, and can further expand or reorganize these properties and methods according to their own needs. Write.

Composition is when a class is composed of other classes, called member variables or components. Through combination, a class can achieve more complex functions, and its components can be replaced or changed at any time. Composition implements a "has-a" (has one) relationship, where one class owns objects of other classes. For example, a car has components such as engine and tires, and these components can be regarded as member variables of the car class.

Aggregation refers to a relationship between a whole and a part, indicating that an individual can generally exist independently of the whole. In an aggregate, a class can contain objects of other classes, but the contained objects can also not belong to the aggregate object. Aggregation is a weaker, more ambiguous relationship than composition. For example, a school contains multiple classes, and classes are aggregated objects that can exist independently, that is, a class can be migrated to another school.

Java gives an example to illustrate the difference between inheritance, composition and aggregation

Here is a simple Java code example to illustrate the difference between inheritance, composition and aggregation:

继承:
// 定义一个Animal基类
public class Animal {
    private String name;
    private int age;

    // Animal类构造方法
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Animal类方法
    public void eat() {
        System.out.println("Animal is eating.");
    }
}

// 继承
public class Dog extends Animal {
    private String barkSound;

    // 继承Animal类的构造方法
    public Dog(String name, int age, String barkSound) {
        super(name, age);
        this.barkSound = barkSound;
    }

    // 重写Animal类的方法
    @Override
    public void eat() {
        System.out.println("Dog is eating.");
    }

    public void bark() {
        System.out.println(barkSound);
    }
}


UML Class Diagram - Inheritance


// 组合
public class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public void start() {
        engine.start();
    }
}

public class Engine {
    public void start() {
        System.out.println("Engine is starting.");
    }
}

Combination is a relationship between a part and a whole. A part cannot exist without the whole. The Engine here cannot exist without the Car. If this example is not easy to understand, let me give another example, the relationship between the company and the department. The department cannot leave the company and exist alone
UML Class Diagram - Composition


// 聚合
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Classroom {
    private List<Student> students;

    public Classroom(List<Student> students) {
        this.students = students;
    }
}

Aggregation here is also a part-to-whole relationship, but a part can exist without the whole. For example, a Student can exist without a CalssRoom. For example, the relationship between a department and an employee can exist independently without a department.
UML Class Diagram - Aggregation

测试:

public class Test {
    public static void main(String[] args) {
        // 继承
        Dog dog = new Dog("小黑", 2, "汪汪汪");
        dog.eat();
        dog.bark();

        // 组合
        Engine engine = new Engine();
        Car car = new Car(engine);
        car.start();

        // 聚合
        Student stu1 = new Student("小明", 18);
        Student stu2 = new Student("小红", 19);
        List<Student> students = new ArrayList<Student>();
        students.add(stu1);
        students.add(stu2);
        Classroom classroom = new Classroom(students);
    }
}

Summarize

The following is a summary of the application scenarios of inheritance, composition and aggregation:

Inheritance: Inheritance is often used to implement the "is-a" (is one) relationship. For example, the Animal class is the base class, and the Dog class and Cat class are its derived classes. They are all animals, so they inherit public properties and methods. In addition, inheritance also provides a mechanism for code reuse, which can greatly reduce the amount of program code.

Composition: Composition is often used to implement a "has-a" (has one) relationship. For example, a car has components such as an engine and tires, which can be regarded as member variables of the car class. In addition, through combination, different components can be flexibly combined to achieve more flexible object construction.

Aggregation: Aggregation is often used to realize the relationship between a whole and a part. The relationship is relatively loose, and the components can be replaced or changed at any time. For example, a school contains multiple classes, and classes are aggregated objects that can exist independently, that is, a class can be migrated to another school. The advantage of aggregation is that a "weak coupling" relationship can be established between the whole and the part, allowing flexible changes of the part while maintaining the integrity of the whole.

It should be noted that different application scenarios correspond to different requirements, so the implementation method should be selected according to specific requirements. In actual development, based on the above summary, you can choose the most suitable mechanism to realize the relationship between classes, and try to conform to the basic principles of object-oriented programming when designing, such as the principle of single responsibility, open-closed principle, and Liskov substitution principle wait.

Guess you like

Origin blog.csdn.net/m0_37742400/article/details/130169135