A combination of Java Basics Tutorials (composition) _java

Source: Internet
Author: User
Tags class definition

We have tried to define the class. Define a class, which is to create a new kind (type). With the class, we then construct the object of the corresponding type. Further, each type should also have a clear interface (interface) for use by the user.

We can use other objects in the definition of a new class. This is the combination (composition). Combination is one of the basic means of implementing program reuse (Reusibility) in Java.

Combination and "Has-a"

An object is a data member of another object. For example, let's look at the previous examples of rechargeable torches:

A battery, LED light, button in a rechargeable flashlight ... Can be an object. We can define a battery class to define and generate a battery object. In the class definition of the rechargeable torch, a battery object can be used as its data member to represent the state of the battery section.

We define a battery class below and use power to represent its electricity. A battery can be recharged (chargebattery) and Used (Usebattery). We use the battery type object as the data member in the subsequent Torch class definition:

Copy Code code as follows:

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/hour use
&NBSP;&NBSP;&NB sp;  * Warning when out of power
     */
    public void turnon (int hours)
    {
        boolean usable;
         usable = This.theBattery.useBattery (hours*0.1);
        if (usable!= true) {
       & nbsp;    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 essential.

We define the battery class. The Torch class uses an object of battery type (thebattery) as a data member. In the torch approach, we implement the functionality (functionality) provided by the battery class by manipulating the interface of the Thebattery object.

We say that a Torch object owns (has-a) a battery object. The above relationship can be expressed as:

Has-a: The flashlight has a battery (note the diamond connection above)

By combining, we can reuse battery-related code. If we have other classes that use battery, such as cell phones and calculators, we can combine battery objects. This makes it not necessary to write related functionality for each class individually.

We can add a test class to see the actual effect:

Copy Code code as follows:

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 ("The Turn On:3 hours");
Atorch.turnon (3);
System.out.println ("Second Turn on:3 Hours");
Atorch.turnon (3);
}
}

The results of the above program:

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

We use a combination of the functionality provided by the battery object, such as whether the probe is exhausted (according to the return value of the Usebattery ()).

Basic type

From HelloWorld to object-oriented, we'll call int, float, double, boolean, and so on as the basic type (primitive type), which is the special class. We can interpret an integer as an object of type int. int type can have assignment, addition, subtraction and other operating interfaces. Common types can be viewed as an extension of the basic type. We have seen the basic types as data members, the parameters of methods, the return values of methods, and the automatic variables within methods. Naturally, ordinary types of objects, such as battery and torch, can also be used in these places.

C language, the available data types (basically) have been preset, such as int, float. In Java, in addition to using these preset data types, we can customize the data types we want by using classes, and then use them in combination. But there is a difference between the basic type and the common type. Basic types are often used and have little memory footprint, so in Java, for efficiency, these basic types are different from the memory management of ordinary types (that is, custom classes). For example, a basic type is allocated memory space once it is declared, and the normal type needs to use the New keyword to allocate the memory space.

Java provides the corresponding generic type for each basic type. For example, int basic type corresponds to integer type. If you convert an object of the base type to the corresponding generic type variable, the so-called basic type becomes a generic type (no more different in memory management).

In this way, we have a deeper understanding of the Java "all objects" concept.

Summarize

Combination, has-a

Basic type

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.