如何从重写的子类方法调用超类的继承方法?

基拉·K

我有一个具有 toString() 方法的类形状我有另一个扩展形状的这个类覆盖了继承的 toString() 方法。我想要做的就是调用父类-形状的从toString()方法圆的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;
}

请帮忙!

TJ克劳德

你会使用super.

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章