我觉得我应该将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);
}
}
答案 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
类,子类可以按照自己的意愿覆盖。