首页 > 代码库 > 【Java 基础篇】【第七课】组合

【Java 基础篇】【第七课】组合

我所理解的组合就是在一个类当中又包含了另一个类的对象。

这样的方式就是组合吧:

电池是一个类,有电量

手电筒需要电池

 

看代码吧:

 1 // 电池类 2 class Battery 3 { 4     // 充电 5     public void chargeBattery(double p) 6     { 7         power += p; 8         System.out.println("Battery: power is " + power ); 9     }10     // 放电11     public boolean useBattery(double p)12     {13         if (power >p )14         {15             power -= p;16             System.out.println("Battery: power is " + power );17             return true;18         }19         else 20         {21             power = 0.0;22             System.out.println("Battery: power only is " + power +", not enough");23             return false;24         }25     }26     // 电量27     private double power = 0.0;28 }29 30 31 // 手电筒类32 class Torch33 {34     // 打开手电筒35     public void turnon(int hours)36     {37         System.out.println("Torch:turnon " + hours + " hours.");38         39         if ( theBattery.useBattery( hours*0.1) == false )40         {41             System.out.println("Torch:can not use, please charge! ");42         }43     }44     45     //手电充电46     public void charge(int hours)47     {48         System.out.println("Torch:charge " + hours + " hours.");49         theBattery.chargeBattery( hours*0.2 );50     }51     52     //电池类53     private Battery theBattery = new Battery();54 }55 56 57 public class test58 {59     public static void main(String[] args)60     {61         Torch aTorch = new Torch();62         aTorch.charge(2);63         aTorch.turnon(3);64         aTorch.turnon(3);65     }66 67 }

运行结果为:
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!

 

主要就是一个面向对象的一个思想,很好理解~~

【Java 基础篇】【第七课】组合