我所理解的组合就是在一个类当中又包含了另外一个类的对象。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