-2

I have a class shape that has a toString() method. I have another class circle that extends shape. This circle class overrides the inherited toString() method. What I want to do is call the superclass - shape's toString() method from inside the circle's toString() method. The following is what I have done as of now. I thought calling toString() in the toString() of the circle might invoke the inherited toString() but that just goes into an infinite loop.

Shape class:

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;
}
}

Circle class:

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;
}

Please Help!

Kiera.K
  • 317
  • 1
  • 13

2 Answers2

0

You'd use super.:

// In Circle
public String toString() {
    String shapeString = super.toString();
    // ...
    return /*...*/;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You must call super.toString() inside the overriding method.

Ghayth
  • 894
  • 2
  • 7
  • 18