【发布时间】:2019-01-29 07:11:50
【问题描述】:
我正在尝试修改 toString 方法。我有一个名为“p”的对象,它有 2 个属性作为属性,在这种情况下,5.0 和 6.0 分别是“x”和“y”值。
字符串转换器“”内的括号应该打印 p 的“x”,p 的“y”,而在圆中它应该打印半径。果然打印半径有效,但我不确定我应该如何指定 p 的“x”和 p 的“y”。
班级圈子:
package packageName;
public class Circle {
public Point center;
public double radius;
public Circle(Point a, double b) {
this.center = a;
this.radius = b;
}
public String toString() {
String converter = "<Circle(<Point(" + (x of p) + ", " + (y of p) + ")>, " + this.radius + ")>";
return converter;
}
public static void main(String args []) {
Point p = new Point(5.0, 6.0);
Circle c = new Circle(p, 4.0);
c.toString();
}
}
课点:
package packageName;
public class Point{
public double x;
public double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
String input = "<Point(" + this.x + ", " + this.y + ")>";
return input;
}
}
【问题讨论】:
-
第 1 步:将变量声明为私有而不是公有。第 2 步:实现 getter/setter 方法
-
或者只使用
p.toString ();的值