【问题标题】:How to modify string returned from super function如何修改从超级函数返回的字符串
【发布时间】:2015-10-02 12:37:08
【问题描述】:

这是我的 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();
}

【问题讨论】:

    标签: java string stringbuilder


    【解决方案1】:

    而不是

    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.
    

    【讨论】:

      【解决方案2】:

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

      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() 的确切措辞的依赖。想象一下,您将 Quadrilateral 的 toString() 消息更改为“四边形的坐标 ...” - 如果这样做,您将不得不修改 Trapezoid(可能还有其他子类)中的索引 (16, 28) 或者它的 toString( ) 将打印“坐标梯形...”

      【讨论】:

      • 非常真实,非常有帮助。我打算试试你的方法。
      【解决方案3】:

      使用

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2011-12-30
        • 1970-01-01
        • 2010-12-23
        相关资源
        最近更新 更多