我有一个具有toString()方法的类 shape 。我还有另外一个圆形类,可以扩展形状。该 circle 类重写了继承的toString()方法。我想做的是从 inside 内的 circles toString()方法调用超类- shapes toString()方法。以下是我到目前为止所做的事情。我以为在圆圈的toString()中调用toString()可能会调用继承的toString(),但这只会陷入无限循环。
形状类:
class shape{
String color;
boolean filled;
shape()
{
color = "green";
filled = true;
}
shape(String color, boolean fill)
{
this.color = color;
this.filled = fill;
}
public String toString()
{
String str = "A Shape with color = " + color + " and filled = " + filled + " .";
return str;
}
}
圈子类别:
class circle extends shape
{
double radius;
circle()
{
this.radius = 1.0;
}
public String toString()
{
String str = "A circle with radius " + radius + " and which is a subclass of " + toString();
return str;
}
请帮助!
答案 0 :(得分:0)
您将使用super.
:
// In Circle
public String toString() {
String shapeString = super.toString();
// ...
return /*...*/;
}
答案 1 :(得分:0)
您必须在覆盖方法内调用super.toString()。