日期:2014-05-20  浏览次数:20711 次

有关组合(composition)的问题,请求好心人回答?
class   CommissionEmployee
{
      protected   String   firstName;
      public   CommissionEmployee(   String   first   )
      {
            firstName   =   first;

      }  
      public   void   setFirstName(   String   first   )
      {
            firstName   =   first;
      }  
      public   String   getFirstName()
      {
            return   firstName;
      }  
      }  

public   class   BasePlusCommissionEmployee  
{
      private   double   baseSalary;  
      private   CommissionEmployee   ce;
      public   BasePlusCommissionEmployee(   String   firstdouble   salary   )
      {
            ce   =   new   CommissionEmployee(   "Bob);
            setBaseSalary(   salary   );  
      }  
     
      public   void   setBaseSalary(   double   salary   )
      {
            baseSalary   =   (   salary   <   0.0   )   ?   0.0   :   salary;
      }  
      public   double   getBaseSalary()
      {
            return   baseSalary;
      }  
}  

class   BasePlusCommissionEmployeeTest  
{
      public   static   void   main(   String   args[]   )  
      {
            BasePlusCommissionEmployee   basePlusCommissionEmployee   =  
                  new   BasePlusCommissionEmployee(  
                  "Bob ",   300   );
            System.out.printf(   "%s   %s\n ",   "First   name   is ",
                  ce.getFirstName()   );
                    System.out.printf(   "%s   %.2f\n ",   "Base   salary   is ",
                  basePlusCommissionEmployee.getBaseSalary()   );
                  }  
}  
这个程序编译时发现错误如下:说不能找到变量ce,怎么回事啊。???

------解决方案--------------------
ce是 BasePlusCommissionEmployee 类的私有变量,在类BasePlusCommissionEmployeeTest 中当然无法访问,建议你修改如下

class CommissionEmployee {
protected String firstName;

public CommissionEmployee(String first) {
firstName = first;

}

public void setFirstName(String first) {
firstName = first;
}