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