2016-08-30 56 views
-1

我有两类形状,一个是矩形,另一个是圆形,都扩展了“形状”类。使用toString()的最有效方法JAVA

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

我想通过重写,使用超级和添加更多的信息,但有一件事看起来很奇怪,在每个类中使用toString方法。我应该为每个方法创建一个新的字符串生成器对象吗?即使它有效,看起来也不太合适。尝试在网上查找它,但到目前为止它或者使用一串字符串。我错过了什么吗?

这里是我在形状阶级都:

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

我是从主要使用对象名称美其名曰的ToString();

+0

对不起,什么是错的,你在做什么? –

+0

确保使用'@ Override'。究竟是什么错误? – Li357

+0

为每种方法创建一个新的对象似乎是错误的 –

回答

1

的显而易见的问题是

  1. 在你RectangleCircle类,你叫super.toString(),什么也不做,结果。没有理由称之为。或者,我猜你正在尝试做的是这样的:(例如Rectangle

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

    例如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

使用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); 

    } 

}