最有效的方法是使用toString()JAVA

时间:2016-08-30 05:30:54

标签: java tostring

我有两类形状,一类是矩形,第二类是圆形,两者都延伸"形状"类。

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

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

这是我在形状类中所做的:

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

矩形类:

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

圈子类:

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调用它们

2 个答案:

答案 0 :(得分:1)

明显的问题是

  1. 在您的RectangleCircle课程中,您拨打了super.toString()并对结果不执行任何操作。没有理由说它。或者,我猜你要做的是:(例如Rectangle

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

    e.g。 Shape

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

    足够好了。永远使用StringBuilder不是更好。

答案 1 :(得分:-1)

使用System.out.println(super.toString()打印/使用超类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);

    }

}
相关问题