Relationships between classes in Java

Source: Internet
Author: User

The relationships between classes in Java include the following:

1. Generalization)

It is very simple, that is, the inheritance we often say. It means that sub-classes can obtain the features of the parent class and expand their own functions.

:

 

 

Java code: extends and implements

2. Dependency)

When a is responsible for constructing B, A and B form a dependency, that is, a uses B.

 

 

Java code shows local variables, method parameters, and calls to static methods.

3. Association)

Two relatively independent things (a and B) form an association when object a holds object B.

There are two special forms: Aggregation and composition. There is only a conceptual difference between aggregation and combination, and there is no difference in code implementation in Java.

Aggregation: refers to the relationship between the whole and the part,

 

 

Combination: indicates the relationship between the whole and the part of the class, but the partial and the whole of the combination have a unified lifetime, that is, the whole object does not exist, and some objects will not exist,

 

 

In Java code, it is represented as a member variable.

4. Summary

In Java, the combination should be used as much as possible, instead of inheritance, because inheritance will complicate the class relationship too much and undermine encapsulation. Using the combination can also obtain the functions of existing classes, it also makes the new class more stable.

In fact, from the dependency -----> aggregate --------> combination, the relationship between classes is more closely, and the influence between classes is getting greater and greater. In fact, we usually do not distinguish between these relationships, in fact, this definition is not very easy to understand, so it will certainly lead to deviations in understanding. So when we use these things, try to be close to what everyone agrees, this makes it easy for others to understand.

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.