我正在从https://www3.ntu.edu.sg进行OOP练习,我无法找出一个继承问题。我们有两个类:超类circle
和子类cylinder
extends
circle
。
界:
public double getArea() {
return Math.PI*radius*radius;
}
public String toString() {
return "Circle Area: "+this.getArea()";
}
圆柱延伸圆
@Override
public double getArea() {
// TODO Auto-generated method stub
return super.getArea()*2+super.getCircumference()*height;
}
@Override
public String toString() {
return "Cylinder["+super.toString+"]"+"Cylinder area="+getArea()+"]";
}
新对象类型Cylinder
使用super.toString()
类中的getArea()
打印Cylinder
- 打印cylinder
区域的两个区域。如何在Circles
中使用超类(getArea()
)super.toString
?
谢谢!
答案 0 :(得分:0)
在运行时this
代表对象的当前实例,这是Cylinder
方法getArea()
。因此,继承对我们没有帮助。
解决方法是以这种方式更改Circle
类:
private double getCircleArea() {
return Math.PI*radius*radius;
}
public double getArea() {
return getCircleArea();
}
public String toString() {
return "Circle Area: " + this.getCircleArea();
}