We have tried to define the class. Defines a class, which is a new type. With the class, we then construct the object of the corresponding type. Further, each type should also have a clear interface (interface)for the user to use.
We can use other objects in the definition of a new class. This is the combination (composition). composition is one of the basic means of implementing program reuse (Reusibility) in Java.
We define a battery class below and use power to represent its power. A battery can be recharged (chargebattery) and Used (Usebattery). We use objects of the battery type as data members in the subsequent Torch class definition:
classBattery { Public voidChargebattery (Doublep) {if( This. Power < 1.) { This. Power = This. Power +p; } } Public BooleanUsebattery (Doublep) {if( This. Power >=p) { This. Power = This. Power-p; return true; } Else { This. Power = 0.0; return false; } } Private DoublePower = 0.0;}classtorch{/*** 10% power per hour use * Warning if out of power*/ Public voidTurnOn (inthours) { Booleanusable; Usable= This. Thebattery.usebattery (hours*0.1 ); if(Usable! =true) {System.out.println ("No more usable, must charge!"); } } /*** 20% power per hour charge*/ Public voidChargeinthours) { This. Thebattery.chargebattery (hours*0.2 ); } /*** Composition*/ PrivateBattery Thebattery =NewBattery ();}
The above new allocates memory for the Thebattery object, which is indispensable.
We define the battery class. The Torch class uses an object of type battery (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:
By combining, we can reuse battery-related code. If we have other classes that use battery, such as mobile phones and calculators, we can combine battery objects. This makes it not necessary to write a separate function for each class.
We can add a test class To see the actual effect:
Public class test{ publicstaticvoid main (string[] args) { 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);} }
The operation 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 a combination of functions provided by the battery object, such as detecting whether the charge is exhausted (based on the return value of Usebattery ()).
Java Basic Learning--11, combination