【问题标题】:How do I use a specific variable of an object that is in another class?如何使用另一个类中的对象的特定变量?
【发布时间】: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 ();的值

标签: java class methods


【解决方案1】:

你说你想在CirlcetoString方法中打印“p”的“x”和“p”的“y”,但是toStringp一无所知,因为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 来表示“foo 的bar”的。这是点符号,您似乎对此不熟悉。

【讨论】:

    【解决方案2】:

    pmain方法的局部变量,所以变量p本身不能用在你想用的地方。

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

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

    this.center.x
    

    【讨论】:

      【解决方案3】:

      你可以使用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 + ")>"; 
      

      【讨论】:

      • 有趣,为什么我必须将变量设为私有才能使用 getter?
      • 其实在使用类的时候,它的实例变量应该是私有的。这实际上支持抽象属性。这是将实例变量设为私有和使用 getter/setter 方法的好习惯。
      猜你喜欢
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2020-12-11
      • 1970-01-01
      • 2018-10-27
      • 2020-03-28
      相关资源
      最近更新 更多