使用toString()JAVA的最有效方法
我有两类形状,一类是矩形,第二类是圆形,它们都扩展了“形状”类 我应该打印每个类的相关信息,例如x,y代表一个与所有形状和颜色相关的点。 矩形类有其宽度和高度,圆有半径 我试图通过重写、使用super和添加更多信息在每个类中使用toString方法,但有一件事看起来很奇怪。我应该为每个方法创建一个新的字符串生成器对象吗?即使它能工作,看起来也不太对劲。尝试在网上查找,但到目前为止不是这样就是使用了一堆字符串。我错过什么了吗 以下是我在形体课上所做的:使用toString()JAVA的最有效方法,java,tostring,Java,Tostring,我有两类形状,一类是矩形,第二类是圆形,它们都扩展了“形状”类 我应该打印每个类的相关信息,例如x,y代表一个与所有形状和颜色相关的点。 矩形类有其宽度和高度,圆有半径 我试图通过重写、使用super和添加更多信息在每个类中使用toString方法,但有一件事看起来很奇怪。我应该为每个方法创建一个新的字符串生成器对象吗?即使它能工作,看起来也不太对劲。尝试在网上查找,但到目前为止不是这样就是使用了一堆字符串。我错过什么了吗 以下是我在形体课上所做的: public String 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();
}
我使用object name.toString()从main调用它们 显而易见的问题是
矩形
和圆形
类中,调用了super.toString()
,对结果不做任何处理。没有理由这样称呼它。或者,我猜你想做的是:(例如,矩形
)
StringBuilder
。简单地
e、 g.Shape
class
public String toString() {
return "The x axis is: " + x
+ " and the y axis is:" + y
+ " The color of " + this.getClass().getSimpleName()
+ " is " + color;
}
这已经足够好了。始终使用StringBuilder不是更好的选择使用
System.out.println(super.toString()
打印/使用super类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);
}
}
很抱歉,您正在执行的操作有什么问题?请确保使用
@Override
。到底是什么问题?为每个方法创建新对象似乎是错误的
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);
}
}