当前位置: 代码迷 >> J2SE >> 有关组合(composition)的有关问题,请求好心人回答
  详细解决方案

有关组合(composition)的有关问题,请求好心人回答

热度:87   发布时间:2016-04-24 15:09:41.0
有关组合(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;
}