Java子类有一个重复的方法

时间:2016-06-02 19:42:13

标签: java inheritance subclass

我觉得我应该将computeResults()方法从子类移到父类,因为它们是相同的,但是当我做的时候Eclipse警告父The method computeField3() and computeField4() are undefined for the type Parent也许我不完全理解继承。
我可以按照下面的方式编译类,但是我的子类不遵循不重复自己的主体吗?或者我的课程定义得当吗?

public class Parent {
   private BigDecimal field1;
   private BigDecimal field2;
   protected BigDecimal field3;
   protected BigDecimal field4;

   protected void computeField1() {
     // math equation identical b/n all subclasses
     setField1(value);
   }
   protected void computeField2() {
     // math equation identical b/n all subclasses
     setField2(value);
   }
}

public class Child1 extends Parent {
    void computeResults() {
      // This method is redundant and I would like to move to Parent
      computeField1(); 
      computeField2(); 
      computeField3(); 
      computeField4(); 
    }


   private void computeField3() {
     // math equation for Child1 and Child2 differs for field3 
     setField3(value);
   }
   private void computeField4() {
     // math equation for Child1 and Child2 differs for field4 
     setField4(value);
   }
}

public class Child2 extends Parent {
    void computeResults() {
      // This method is redundant and I would like to move to Parent
      computeField1(); 
      computeField2(); 
      computeField3(); 
      computeField4(); 
    }

   private void computeField3() {
     // math equation for Child1 and Child2 differs for field3 
     setField3(value);
   }
   private void computeField4() {
     // math equation for Child1 and Child2 differs for field4 
     setField4(value);
   }
}

1 个答案:

答案 0 :(得分:0)

您的问题是,当您将computeResults移至父级时,使其代码看起来像

public class Parent {
   private BigDecimal field1;
   private BigDecimal field2;
   protected BigDecimal field3;
   protected BigDecimal field4;

   void computeResults() {
     computeField1(); 
     computeField2(); 
     computeField3(); 
     computeField4(); 
   }
   protected void computeField1() {
     // math equation identical b/n all subclasses
     setField1(value);
   }
   protected void computeField2() {
     // math equation identical b/n all subclasses
     setField2(value);
   }
}

它会尝试拨打computeField3 / 4,但找不到它们,因为它们不存在于您的代码Parent 中。< / p>

因此,您需要将computeField3 / 4添加到Parent类,子类可以按照自己的意愿覆盖。