Java basics 06 combination

Source: Internet
Author: User

 

We have tried to define the class. Defines a class, that is, a new type is created ). With the class, we 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 the composition ). Combination is one of the basic methods for implementing reusibility in Java.

 

Combination and "has-"
An object is a data member of another object. For example, let's take a look at the example of the charging record mentioned earlier:

 

A battery, LED lamp, and button in a rechargeable worker ...... Can be an object. We can define a Battery class to define and generate Battery objects. A battery object can be used as a data member to represent the status of the battery part in the definition of the charge consumer class.

 

 

The following defines a Battery class and uses power to represent its power. One Battery can be charged (chargeBattery) and used (useBattery ). In the subsequent Torch class definition, we use an object of the Battery type as a data member:


Class Battery
{
Public void chargeBattery (double p)
{
If (this. power <1 .){
This. power = this. power + p;
}
}

Public boolean useBattery (double p)
{
If (this. power> = p ){
This. power = this. power-p;
Return true;
}
Else {
This. power = 0.0;
Return false;
}
}

Private double power = 0.0;
}

Class Torch
{/*** 10% power per hour use * warning when out of power */
Public void turnOn (int hours)
{
Boolean usable;
Usable = this. theBattery. useBattery (hours * 0.1 );
If (usable! = True ){
System. out. println ("No more usable, must charge! ");
}
}
/*** 20% power per hour charge */
Public void charge (int hours)
{
This. theBattery. chargeBattery (hours * 0.2 );
}

/**
* Composition
*/
Private Battery theBattery = new Battery ();
} The new above allocates memory for the theBattery object, which is indispensable.

We define the Battery class. The Torch class uses a Battery object (theBattery) as a data member. In the Torch method, we can manipulate the theBattery object interface to implement the function provided by the Battery class (functionality ).

We say that a Torch object owns (has-a) a Battery object. The preceding relationship can be expressed:

 

Has-a: battery in the flashlight (pay attention

 

Diamond line)

Through combination, We can reuse Battery-related code. If we have other Battery classes, such as cell phones and calculators, we can combine Battery objects. In this way, you do not need to write related functions for each class.

 

We can add a Test class to see the actual results:


Public class Test
{
Public static void main (String [] args)
{
Torch aTorch = new Torch ();
System. out. println ("Charge: 2 hours ");
ATorch. charge (2 );
System. out. println ("First Turn On: 3 hours ");
ATorch. turnOn (3 );
System. out. println ("Second Turn On: 3 hours ");
ATorch. turnOn (3 );
}
} Running result of the above program:

Charge: 2 hours
First Turn On: 3 hours
Second Turn On: 3 hours
No more usable, must charge!

We use the functions provided by the battery object through combination, such as checking whether the power usage is exhausted (according to the return value of useBattery ).

 

Basic Type
From HelloWorld to object-oriented, we call int, float, double, boolean, and so on the basic type (primitive type), which is a special class. We can understand an integer as an int type object. Int type can have operation interfaces such as value assignment, addition, and subtraction. Common types can be considered as extensions of basic types. We have seen basic types as data members, method parameters, method return values, and internal automatic variables of methods. Naturally, common objects, such as Battery and Torch objects, can also be used in these places.

In C language, the available data types (basically) have been preset, such as int and float. In Java, in addition to the predefined data types, we can also customize the desired data types through classes and use them in combination. However, the basic type is different from the common type. The basic types are often used and occupy little memory space. Therefore, in Java, for efficiency, these basic types and common types (that is, custom classes) memory management methods are different. For example, if the basic type is declared, the memory space will be allocated, and the general type needs to use the new keyword to allocate the memory space.

Java provides a common type for each basic type. For example, the basic int type corresponds to the Integer type. If you convert an object of the basic type to a common variable, the so-called basic type becomes a general type (there is no memory management difference ).

In this way, we have a deeper understanding of the concept of "Everything is an object" in Java.

 

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.