Re-understanding Java (iv)-combination, aggregation and inheritance of love and hate

Source: Internet
Author: User

Some have learned that inheritance, that he is one of the object-oriented features, in all can be used to inherit the place of inheritance, regardless of whether it should not be used, undoubtedly, this is wrong. So, how do you use inheritance?

Relationships between classes and classes in Java

Most beginners only know that two classes in Java can be inherited and inherited, but in fact, there are basically five types of relationships between classes-inheritance (Implementation), dependencies, associations, aggregations, and combinations.

Next, simply analyze these relationships.

Inheritance (Implementation)

For classes, this relationship is called inheritance, and for interfaces, this relationship is called implementation. Inherit the previous article has been explained in detail, as for the realization, I think we all know what is going on, because the latter to specifically talk about the interface, so here is not to say first. Inheritance is a kind of "is-a" relationship.

Dependent

A simple understanding of dependency is that a method in Class A uses another Class B.

This use relationship is accidental, temporary, and very weak, but changes in class B affect a.

For example, I write with a pen, first need a class to represent myself, and then need a class to represent a pen, and finally, ' I ' to call the ' pen ' method to write, in code implementation:

publicclass Pen {    publicvoidwrite(){        System.out.println("use pen to write");    }}publicclass Me {    publicvoidwrite(Pen pen){//这里,pen作为Me类方法的参数        pen.write();    }}

See this everyone understand, because this code you will write every day. Now you know, this is a relationship between classes and classes, called dependencies.

This relationship is a very weak relationship, but the change of the pen class may affect the results of the Me class, for example, I have modified the method of the pen class write method, and I will get different results when I call it again.

In general, dependencies are represented in Java as local variables, method parameters, or calls to static methods.

Associate

Correlation is a strong dependency between two classes, or the semantic level of a class and an interface.

This relationship is more than relying on a more strong, no dependence on the contingency, the relationship is not temporary, generally long-term, and the relationship between the two sides is generally equal, the association can be one-way, two-way.

Look at the following code:

// pen 还是上面的penpublicclass You {    private// 让pen成为you的类属性     publicYou(Pen p){        this.pen = p;    }    publicvoidwrite(){        pen.write();    }}

The associated Class B appears as a class attribute in the association Class A, or the association Class A refers to a relationship of a type that is a global variable of the associated class B, which is called an association relationship.

In Java, association relationships are typically implemented using member variables.

Aggregation

Aggregation is a special case of association, and he embodies the relationship between the whole and the part, and the has-a .

Look at the following section of code:

publicclass Family {    private//一个家庭里有许多孩子    // ...}

At the code level, aggregation and association relationships are consistent and can only be differentiated from the semantic level. In the common relation, the Class A and Class B do not have the necessary relation, but in the aggregation, the Class B is a part of Class A, and it is a "has-a" relationship, i.e. a has-a B; For example, the family has children, the room is air-conditioned.

However, has not must has,a can have B, or can not. A is the whole, B is the part, the whole and the parts are separable, they can have their own life cycle, some can belong to multiple whole objects, or can be shared for multiple whole objects.

The status of the two classes in the aggregation relationship is unequal, unlike the equal status of the association relationship.

Combination

The combination is also a special case of the association relationship, he embodies a contains-a relationship, which is stronger than aggregation, also known as strong aggregation.

Look at the code first:

publicclass Nose {    privatenew Eye();  //一个人有鼻子有眼睛    privatenew Nose();    // .... }

The combination also embodies the relationship between the whole and the part, but at this time the whole and the part are not divided, the whole life cycle end also means that part of the life cycle ends.

Just as you have a nose with eyes, if you accidentally end the life cycle, the life cycle of the nose and eyes will also end, and the nose and eyes cannot be separated from you alone.

Just look at the code, you are unable to distinguish between associations, aggregations and combinations, specifically which kind of relationship can only be differentiated from the semantic level.

Similarly, in the combinatorial relationship, the two-class-sum relationship is unequal.

grouping, aggregation, and inheritance

Dependencies are every Java program can not be separated, so it is not discussed separately, the common relationship is not a special place, the following we focus on the combination, aggregation and inheritance.

Aggregation and Composition
    1. Aggregation and composition are an association relationship, but the extra has a whole-part meaning.

    2. Parts have a different life cycle

      • In an aggregation relationship, the entire piece does not have a life cycle of the part, so the part is not deleted when the whole piece is deleted. Furthermore, multiple pieces can share the same part.

      • In a composite relationship, the entire piece has a life cycle of the part, so the part must be deleted when the whole piece is deleted. Also, multiple pieces cannot share the same part at the same time.

      This distinction can be used to distinguish whether an association is a combination or an aggregation. The two class life cycle is not synchronized, it is the aggregation relationship, and the life cycle synchronization is the combination relationship.

    3. The aggregation relationship is a "has-a" relationship, and the combined relationship is a "contains-a" relationship.

      Usually we only discuss the combination and inheritance, think the combination is "has-a" relationship, and in fact, the aggregation is the real "has-a" relationship, the combination is a deeper "contains-a" relationship.

      Because the "contains-a" relationship is a deeper "has-a" relationship, it is also true that the combination is a "has-a" relationship.

Composition and Inheritance

This is the focus of this article.

Learn the design patterns know, to "less use inheritance, multi-use combination", this is why?

Let's take a look at the pros and cons of combining and inheriting each:

advantages and disadvantages of composition and inheritance

Combination

Advantages:

- 不破坏封装,整体类与局部类之间松耦合,彼此相对独立- 具有较好的可扩展性- 支持动态组合。在运行时,整体对象可以选择不同类型的局部对象- 整体类可以对局部类进行包装,封装局部类的接口,提供新的接口

Disadvantages:

- 整体类不能自动获得和局部类同样的接口- 创建整体类的对象时,需要创建所有局部类的对象

Defect Analysis:

1, the whole class can not automatically get the same interface as the local class

如果父类的方法子类中几乎都要暴露出去,这时可能会觉得使用组合很不方便,使用继承似乎更简单方便。但从另一个角度讲,实际上也许子类中并不需要暴露这些方法,客户端组合应用就可以了。所以上边推荐不要继承那些不是为了继承而设计的类,一般为了继承而设计的类都是抽象类。

2. When creating an object of a whole class, you need to create objects of all local classes

这个可能没什么更好的办法,但在实际应用中并没有多出多少代码。

Inherited

Advantages:

- 子类能自动继承父类的接口- 创建子类的对象时,无须创建父类的对象

Disadvantages:

- 破坏封装,子类与父类之间紧密耦合,子类依赖于父类的实现,子类缺乏独立性- 支持扩展,但是往往以增加系统结构的复杂度为代价- 不支持动态继承。在运行时,子类无法选择不同的父类- 子类不能改变父类的接口

Defect Analysis:

1. Why does inheritance destroy encapsulation?

Ducks do not want to "fly" the method, but because the inheritance cannot encapsulate this useless "fly" method.

2, why the inheritance of tight coupling:

When you feel that the insert name is inappropriate in the basetable of the parent class, if you want to modify it to the Create method, the Insert method using the subclass object will compile an error, and you might find it easier to change it. Because there are refactoring tools all at once and the compilation errors are easy to change. But if basetable and subclasses are in different assemblies, maintaining different people, basetable assembly upgrades, the code that could have been used suddenly can't be used, which is still hard to accept

3. Why inheritance is more complex to expand

When books and digital tax methods are the same as digital products, and when consumer products are taxed in another way, the adoption of succession schemes may evolve into the following ways:

Thus, if the product continues to increase, the tax method continues to increase, the hierarchy of inheritance will be very complex, and difficult to control, and the use of combination can be a good solution to this problem

4. Inheritance cannot support dynamic inheritance

This is actually very good understanding, because the inheritance is the compilation period decided down, can not be changed at runtime, such as 3 cases, if the user needs to choose the tax method according to local circumstances, the use of inheritance can not be solved, and the use of combination of reflection can be a good solution.

5, why inherit, subclass cannot change parent class interface

As shown in Figure 2, the subclass finds the Insert method inappropriate and wants to use the Create method because the reason for the inheritance cannot be changed

differences and linkages between combinations and inheritance
  • In an inheritance structure, the inner details of the parent class are visible to the child class. So we can often say that code reuse through inheritance is a white-box code reuse. (If the implementation of the base class changes, the implementation of the derived class will change as well.) This results in unpredictable behavior of the subclass)

  • A combination is the creation of new, more complex functions by assembling (combining) existing objects. Because the internal details are not visible between the objects, we also say that the code reuse in this way is black-box code reuse. (because a type is generally defined in a composition, it is not known at compile time which method of the implementation class will be called at all)

  • Inheritance when writing code to specify which class to inherit, so, in the compilation period to determine the relationship. (implementations inherited from the base class cannot be dynamically changed at run time, thus reducing the flexibility of the application.) )

  • Combination, you can use interface-oriented programming when writing code. Therefore, the combination of classes is generally determined at run time.

  • A combination (has-a) relationship can explicitly obtain an object that is contained in a class (known as the parent class in inheritance), whereas inheritance (IS-A) implicitly obtains the object of the parent class, which corresponds to the containing class and the parent class, and the combined outer class and subclass.

  • A combination is a loosely coupled relationship between a combined class and a contained class, whereas inheritance is a tightly coupled relationship between a parent class and a subclass.

  • When you choose to use a composition relationship, an object of the outer class is included in the composition class, the combined class can invoke the methods that are required by the external class, and when you use an inheritance relationship, all the methods and variables of the parent class are unconditionally inherited, and the subclass cannot be selected.

  • Most importantly, when using an inheritance relationship, you can implement the backtracking of a type, that is, referencing the subclass object with the parent class variable, so that you can implement polymorphism, and the combination does not have this feature.

  • It is also important to note that if you determine that the method of reusing another class never needs to be changed, you should use a combination, because the combination simply re-uses the interface of the containing class, and the inheritance, in addition to reusing the interface of the parent class, can even overwrite those interfaces and modify the default implementation of the parent class interface, which is not a combination

  • Logically, the combination of the most important embodiment is a whole and part of the idea, for example, in the Computer class is composed of memory class, CPU class, hard disk class and so on, and inheritance is a kind of retrospective parent-child relationship, subclass is also an object of the parent class.

  • The difference between the two is mainly reflected in the abstract stage of the class, when analyzing the relationship between classes should be determined whether to adopt a combination or inherit.

  • Quoted netizens a very classic words should be more able to distinguish between inheritance and combination of the difference: The combination can be said to be "I invited an old man to work in my home", inheritance is "my father at home to help me work."

an inheritance or a combination?

First of all, they are the most common and effective design techniques for the reuse of system functions and code reuse, all of which are the basic structures in the design pattern.

Many people know that there is a more important principle in object-oriented "multi-use combination, less inheritance" or "combinatorial better than inheritance". As can be seen from the previous introduction of the pros and cons, the combination is indeed more flexible and more helpful for code maintenance than inheritance.

Therefore, it is advisable to use the combination rather than the inheritance in the same feasible situation. Because the combination is safer, simpler, more flexible, and more efficient.

Note that it is not that inheritance is useless at all, and what is said before is "in the same possible circumstances". There are some scenarios where you need to use inheritance, or it is more appropriate to use inheritance.

Inheritance should be used with caution, and its use is limited to situations in which you are certain that the technology is valid. One way to judge this is to ask yourself if you need to move up from a new class to a base class. If it is required, then inheritance is necessary. Conversely, you should consider whether you need to inherit.

Inheritance is only appropriate if the subclass is really a subclass of a superclass. In other words, for two classes A and B, Class B should inherit Class A only if a is-a relationship does exist between the two.

The upward transformation will be explained in detail in the next article, "Re-understanding Java (v)-object-oriented polymorphism."

Summary

According to what we have said earlier, we can see that inheritance is far more of a disadvantage than merit, although inheritance has been heavily emphasized in the course of learning oop, it does not mean that it should be used everywhere as much as possible. Instead, use it with caution.

It can only be considered if it is well known that inheritance is most effective in all methods. The greatest advantage of inheritance is that the extension is simple, but most of the shortcomings are fatal, but because the advantages of this simple extension is too obvious, many people do not think deeply, so caused too many problems.

Finally, summarize:

1, carefully designed to be used to inherit the class, the inheritance tree should be more stable abstract layer, generally not more than three layers.
2. For classes that are not specifically used for inheritance, prohibit them from being inherited.
3. Prioritize the use of composite relationships to improve the reusability of code.
4, subclasses are a special type, not just a role of the parent class
5, subclass extension, not overwrite or invalidate the function of the parent class

Yes, so much has been written to say: Please use the inheritance carefully, unless you are sure that the non-use inheritance is not!

This article is very rough, because when writing the article has been in the diarrhea ... There will be some changes in the future, for the time being. If there are errors or better explanations, please leave me a message. I am also just a learning person, not a Java great God, so do not guarantee the correctness of the content of the article ~

Reference article:
Http://www.cnblogs.com/nuaalfm/archive/2010/04/23/1718453.html
http://xifangyuhui.iteye.com/blog/819498
Http://www.tuicool.com/articles/u2uUZjb
Http://www.cnblogs.com/jiqing9006/p/5915023.html

This article address: http://blog.csdn.net/qq_31655965/article/details/54645220, the rotor please indicate the source.
Read a few likes.

Re-recognize Java (iv)-combination, aggregation and inheritance of love and hatred

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.