"Java Fundamentals" "Seventh Lesson" combination

Source: Internet
Author: User

The combination I understand is that the object of another class is contained within one class.

The way to do this is to combine it:

Battery is a class that has power

Flashlight needs battery

Look at the code:

1 //Battery Class2 classBattery3 {4     //Charging5      Public voidChargebattery (Doublep)6     {7Power + =p;8System.out.println ("Battery:power is" +power);9     }Ten     //Discharge One      Public BooleanUsebattery (Doublep) A     { -         if(Power >p) -         { thePower-=p; -System.out.println ("Battery:power is" +power); -             return true; -         } +         Else  -         { +Power = 0.0; ASystem.out.println ("Battery:power only" + Power + ", not Enough"); at             return false; -         } -     } -     //Power -     Private DoublePower = 0.0; - } in  -  to //Flashlight Class + classTorch - { the     //turn on the flashlight *      Public voidTurnoninthours) $     {Panax NotoginsengSystem.out.println ("Torch:turnon" + hours + "hours."); -          the         if(Thebattery.usebattery (hours*0.1) = =false ) +         { ASystem.out.println ("Torch:can not use, please charge!"); the         } +     } -      $     //Flashlight Charging $      Public voidChargeinthours) -     { -System.out.println ("Torch:charge" + hours + "hours."); theThebattery.chargebattery (hours*0.2 ); -     }Wuyi      the     //Battery Class -     PrivateBattery Thebattery =NewBattery (); Wu } -  About  $  Public classTest - { -      Public Static voidMain (string[] args) -     { ATorch Atorch =NewTorch (); +Atorch.charge (2); theAtorch.turnon (3); -Atorch.turnon (3); $     } the  the}

The result of the operation is:
Torch:charge 2 hours.
Battery:power is 0.4
Torch:turnon 3 hours.
Battery:power is 0.09999999999999998
Torch:turnon 3 hours.
Battery:power 0.0, not enough
Torch:can not use, please charge!

is mainly an object-oriented idea, very good understanding ~ ~

"Java Fundamentals" "Seventh Lesson" combination

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.