繁体   English   中英

如何使用另一个类中的对象的特定变量?

[英]How do I use a specific variable of an object that is in another class?

我正在尝试修改 toString 方法。 我有一个名为 'p' 的对象,它有 2 个双打属性,在这种情况下,5.0 和 6.0 分别是 'x' 和 'y' 值。

字符串转换器“< Point >”内的括号应该打印 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;

  }
}

您是说要在CirlcetoString方法中打印“p”的“x”和“p”的“y”,但是toStringp Cirlce ,因为pmain方法中本地声明。

main方法中,您创建了p并将其传递给Circle的第一个参数,然后将其分配给center 所以center存储与p相同的东西。 你应该使用center.xcenter.y

String converter = "<Circle(<Point(" + center,x + ", " + center.y + ")>, " + this.radius + ")>";
return converter;

或者,您可以直接调用center.toString()

String converter = "<Circle(" + c.toString() + ", " + this.radius + ")>";
return converter;

请注意我如何使用语法foo.bar来表示“bar of foo”。 这是点符号,您似乎对此不熟悉。

pmain方法的局部变量,因此变量p本身不能在您想要使用它的地方使用。

但我有一个好消息——您将Point实例作为参数传递给Circle构造函数,并将其存储在center字段中。

您可以将其引用为this.center或仅使用center 要引用指定Point实例的x ,请使用

this.center.x

您可以使用 center.x 和 center.y 如下:

String converter = "<Circle(<Point(" + this.center.x + ", " + this.center.y + ")>, " + this.radius + ")>";

或者您只需将 Point 类的 x 和 y 变量设为私有并使用 getter 方法,如下所示:

private double x;
private double y;

public double getX(){
    return this.x;
}
public double getY(){
    return this.y;
}

并使用

String converter = "<Circle(<Point(" + this.center.getX() + ", " + this.center.getY() + ")>, " + this.radius + ")>"; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM