2016-08-30 57 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); 

    } 

}