我所理解的組合就是在一個類當中又包含了另外一個類的對象。java
這樣的方式就是組合吧:ide
電池是一個類,有電量spa
手電筒須要電池orm
看代碼吧:對象
// 電池類 class Battery { // 充電 public void chargeBattery(double p) { power += p; System.out.println("Battery: power is " + power ); } // 放電 public boolean useBattery(double p) { if (power >p ) { power -= p; System.out.println("Battery: power is " + power ); return true; } else { power = 0.0; System.out.println("Battery: power only is " + power +", not enough"); return false; } } // 電量 private double power = 0.0; } // 手電筒類 class Torch { // 打開手電筒 public void turnon(int hours) { System.out.println("Torch:turnon " + hours + " hours."); if ( theBattery.useBattery( hours*0.1) == false ) { System.out.println("Torch:can not use, please charge! "); } } //手電充電 public void charge(int hours) { System.out.println("Torch:charge " + hours + " hours."); theBattery.chargeBattery( hours*0.2 ); } //電池類 private Battery theBattery = new Battery(); } public class test { public static void main(String[] args) { Torch aTorch = new Torch(); aTorch.charge(2); aTorch.turnon(3); aTorch.turnon(3); } }
運行結果爲:
Torch:charge 2 hours.
Battery: power is 0.4
Torch:turnon 3 hours.
Battery: power is 0.09999999999999998
Torch:turnon 3 hours.
Battery: power only is 0.0, not enough
Torch:can not use, please charge!ci
主要就是一個面向對象的一個思想,很好理解~~it