如何修改超级函数返回的字符串

时间:2015-10-02 12:37:09

标签: java string stringbuilder

这是我的toString()函数,它位于超类中。 我希望能够在我的子类中重用此函数,但将其修改为" Trapezoid的坐标"而不是"四边形的坐标"。

我尝试过使用stringbuilder来修改返回值,但它没有用,所以也许我误用了stringbuilder。我想做的是什么,或者我应该将整个方法的代码复制/粘贴到我的子类方法中并修改那里的文本?

public String toString(){   //this function returns a readable view of our quadrilateral object
        String message = new String();
        message = "Coordinates of Quadrilateral are:\n< " + this.point1.getX() + ", " + this.point1.getY() + " >, < " 
                + this.point2.getX() + ", " + this.point2.getY() + " >, < " 
                + this.point3.getX() + ", " + this.point3.getY() + " >, < " 
                + this.point4.getX() + ", " + this.point4.getY() + " >\n";

        return message;
    }

这是我的子类

    //this function returns a readable view of our trapezoid
public String toString(){
    String modify = super.toString();
    StringBuilder sb = new StringBuilder(modify);
    sb.replace(16, 28, "Trapezoid");
    return modify + "\nHeight is: " + getHeight() + "\nArea is: " + getArea();
}

3 个答案:

答案 0 :(得分:1)

而不是

return modify + "\nHeight is: " + getHeight() + "\nArea is: " + getArea();

return sb.toString() + "\nHeight is: " + getHeight() + "\nArea is: " + getArea();

BTW,而不是+,最好使用StringBuilder.append(),就像这样

String modify = super.toString();
StringBuilder sb = new StringBuilder(modify);
sb.replace(16, 28, "Trapezoid");
sb.append("\nHeight is: ").append(getHeight()); // etc.

答案 1 :(得分:1)

比修改超类输出更好的是修改超类,以便子类可以提供适当的形状名称,例如

class Quadrilateral {
    protected String getShapeName() {
        return "Quadrilateral";
    }

    public String toString() {
        String message = "Coordinates of " + getShapeName() + ...
        ...
    }
}

class Trapezoid {
    @Override
    protected String getShapeName() {
        return "Trapezoid";
    }
}

主要的好处是你可以摆脱Trapezoid toString()对超类&#39;的确切措辞的依赖性。的toString()。想象一下,您将Quadrilateral的toString()消息更改为&#34; Quadrilateral的坐标...&#34; - 如果你这样做,你必须修改Trapezoid中的索引(16,28)(或者可能是其他子类),或者它的toString()将打印&#34; coordinatesTrapezoideral ...& #34;

答案 2 :(得分:0)

使用

return sb.toString() + "\nHeight is: " + getHeight() + "\nArea is: " + getArea();