使用 toString() 的最有效方式 JAVA

Most efficient way of using toString() JAVA

我有 2 class 种形状,一种是矩形,另一种是圆形,都延伸 "shape" class.

我应该打印每个 class 的相关信息,例如 x,y 代表与所有形状和颜色相关的点。 矩形 class 有宽度和高度,圆有半径。

我试图通过覆盖、使用 super 和添加更多信息在每个 class 中使用 toString 方法,但有一件事看起来很奇怪。我应该为每个方法创建一个新的字符串生成器对象吗?即使它有效,看起来也不对。尝试在网上查找它,但到目前为止它要么是这个,要么是使用一堆字符串。我错过了什么吗?

这是我在形状上所做的 class:

public String toString() {
        StringBuilder shapeBuilder = new StringBuilder();
        System.out.println(shapeBuilder.append("The x axis is: ").append(x).append(" and the y axis is: ").append(y).append(" The color of ")
        .append(this.getClass().getSimpleName()).append(" is ").append(color));
        return shapeBuilder.toString();
    }

矩形 class:

public String toString() {
        super.toString();
        StringBuilder rectangleBuilder = new StringBuilder();
        System.out.println(rectangleBuilder.append("The height of the rectangle is: ").append(height)
                .append(" And the width is: ").append(width));
        return rectangleBuilder.toString();
    }

圆class:

public String toString() {
        super.toString();
        StringBuilder circleBuilder = new StringBuilder();
        System.out.println(circleBuilder.append("the radius of the circle is: ").append(getRadius()));
        return circleBuilder.toString();
    }

我正在使用对象 name.toString();

从 main 中调用它们

明显的问题是

  1. 在您的 RectangleCircle class 中,您调用了 super.toString() 并且没有对结果进行任何操作。没有理由调用它。或者,我猜你想做的是:(例如 Rectangle

    public String toString() {
        return super.toString() 
               + " height " + this.height 
               + " width " + this.width;
    }
    
  2. 在您的情况下,您不需要明确使用 StringBuilder。简直

    例如Shapeclass

    public String toString() {
         return "The x axis is: " + x 
              + " and the y axis is:" + y 
              + " The color of " + this.getClass().getSimpleName() 
              + " is " + color;
    }
    

    够用了。 Always-use-StringBuilder 不一定更好。

使用System.out.println(super.toString() to print/use super class toString().

代码如下:

 public class Shape {

    int x;
    int y;
    @Override
    public String toString() {
        return "Shape [x=" + x + ", y=" + y + "]";
    }


}


public class Rectangle extends Shape{

    double width,height;

    @Override
    public String toString() {
        System.out.println(super.toString());
        return "Rectangle [width=" + width + ", height=" + height + "]";
    }


    public static void main(String[] args) {
        Rectangle rectangle=new Rectangle();
        rectangle.x=10;
        rectangle.y=30;
        rectangle.width=20;
        rectangle.height=100;

        System.out.println(rectangle);

    }

}