The relationship between Java classes

Overview

The relationship between the classes and the degree of coupling from high to low:

  • It is. Inheritance, realization
  • It has. Combination, polymerization, association
  • use. rely.

Requirements are: high cohesion and low coupling.

inherit

Is the inheritance relationship between Person and Man.

achieve

combination

public class Person {
    // Person和Heart之间是组合
    private Heart h;
    public Person(){
        h=new Heart();
    }
}

Features are: To create an object in the constructor

polymerization

public class Car {
    //聚合
    private Engine e;
    public Car(Engine e){
        this.e = e;
    }
}

Aggregation features are: has the property, and to be used in the constructor, but not created in the constructor method.

Note that a combination of differences: both the opportunity to create a different combination is created when Person was created. Polymerization can be created in the other.

Related

public class Person {
    // Person 和Car之间是关联关系
    private Car c;
    public void setC(Car c){
        this.c=c;
    }
}

It characterized by: not set in the configuration process.

rely

public class Person {
    // 使用-依赖
    public void traval(Train t){
    }
}

Features are: to be used in ordinary methods.

Guess you like

Origin www.cnblogs.com/heenhui2016/p/10963242.html