繁体   English   中英

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

[英]How to modify string returned from super function

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

我尝试使用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();
}

代替

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

尝试

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

顺便说一句,而不是+ ,最好使用StringBuilder.append() ,像这样

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

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

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

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

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

主要好处是您摆脱了梯形的toString()对超类toString()确切措辞的依赖。 假设您将四边形的toString()消息更改为“四边形的坐标...”-如果这样做,则必须修改梯形(以及其他子类)中的索引(16、28)或它的toString( )将显示“ thelinesTrapezoideral ...”

采用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM