简体   繁体   中英

How to modify string returned from super function

Here is my toString() function that lies in the super class. I want to be able to reuse this function in my subclass but modify it to say "Coordinates of Trapezoid" instead of "Coordinates of Quadrilateral".

I've tried using stringbuilder to modify the return value but it didn't work so maybe I'm misusing stringbuilder. Is what I want to do possible or should I just copy/paste the entire method's code into my subclasses method and modify the text there?

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

Here is my subclass

    //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();
}

instead of

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

try

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

BTW, instead of + , it'd be better to use StringBuilder.append() , like this

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

Better than modifying superclass output would be to modify the superclass so that the subclasses can provide the appropriate shape name, eg

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

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

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

The main benefit is that you get rid of the dependency of Trapezoid's toString() on the exact wording of superclass' toString(). Imagine you change the Quadrilateral's toString() message to "The coordinates of Quadrilateral ..." - if you do that, you'll have to modify the indices (16, 28) in Trapezoid (and possibly other subclasses) or it's toString() will print "The coordinatesTrapezoideral ..."

采用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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