我有两类形状,一个是矩形,另一个是圆形,都扩展了“形状”类。使用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();
对不起,什么是错的,你在做什么? –
确保使用'@ Override'。究竟是什么错误? – Li357
为每种方法创建一个新的对象似乎是错误的 –