Composition of basic Java tutorials

We have tried to define classes. To define a class is to create a new type. With classes, we then construct objects of the corresponding type. Furthermore, each type should have a clear interface for users to use.

We can use other objects in the definition of a new class. This is composition. Composition is one of the basic means to realize program reusability in Java.

Combination and "has-a"

An object is a data member of another object. For example, let's look at the example of rechargeable flashlight mentioned earlier:

The battery, LED lamp, button... In a rechargeable flashlight can be an object. We can define a battery class to define and generate battery objects. In the class definition of rechargeable flashlight, a battery object can be used as its data member to represent the state of the battery part.

Let's define a battery class and use power to represent its power. A battery can be charged and used. In the following definition of the torch class, we use the object of battery type as the data member:

From HelloWorld to object-oriented, we call int, float, double, Boolean, etc. primitive types, that is, special classes. We can understand an integer as an object of type int. Int type can have operation interfaces such as assignment, addition and subtraction. Common types can be regarded as an extension of basic types. We've seen basic types as data members, method parameters, method return values, and automatic variables inside methods. Naturally, common types of objects, such as battery and torch objects, can also be used in these places.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>