如何从被覆盖的子类方法调用超类的继承方法?



我有一个具有toString((方法的类形状。我还有另一个扩展形状的类。此圈类重写继承的 toString(( 方法。我想做的是从圆圈的toString(( 方法内部调用超类 -shape 的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;
}

请帮忙!

你会使用super.

// In Circle
public String toString() {
String shapeString = super.toString();
// ...
return /*...*/;
}

您必须在重写方法中调用 super.toString((。

最新更新