【问题标题】:How do I use an object of a class as an instance variable?如何使用类的对象作为实例变量?
【发布时间】:2017-04-16 17:25:12
【问题描述】:

我的教授给了我们这些指示:

这个类应该有两个实例变量:一个整数radius 和一个Point2D 对象center,它表示圆的中心。提供以下功能:一个二参数构造函数,用于初始化实例变量,顺序为半径和中心。

我需要帮助来制作 center 一个实例变量。这就是我所拥有的:

public class Circle
{
//instance variables
   private int radius;
   Point2D center = new Point2D(2,3);

//constructor
   public Circle(int radius, int center)
   {
    this.radius = radius;
    this.center = center;
   }
}

我不知道如何将它用作实例变量,也不知道如何在构造函数方法中对其进行初始化。

【问题讨论】:

  • 你已经有了。
  • 如果我理解你的问题是正确的,那么你所做的是正确的 Point2D center = new Point2D(2,3);是一个实例变量,您将参数从构造函数分配给“中心”实例变量。我认为您对 java variable type 的术语感到困惑。有四种变量类型(参考:docs.oracle.com/javase/tutorial/java/nutsandbolts/…
  • 它无法编译。给我一个错误,上面写着“不兼容的类型:Int 无法转换为 Point2D

标签: java class constructor initialization instance-variables


【解决方案1】:

我认为您可以将构造函数的第二个参数从 int 更改为 Point2D 对象,如下所示:

public class Circle
{
    //instance variables
    private int radius;

    // Remove the initialization from here and move it inside constructor
    Point2D center;

    //constructor
    // Here you change the second parameter from "int center" to "Point2D center"
    public Circle(int radius, Point2D center)
    {
        this.radius = radius;
        this.center = center;
    }
}

这样,您可以在构造函数中初始化实例变量,并且由于您的类不依赖于 Point2D 类,因此可以更轻松地进行测试和填充。

【讨论】:

【解决方案2】:

center 被正确定义为实例变量。但是,由于您在构造函数中要求中心,因此在声明它时无需将其分配给任何东西。您的代码中唯一的错误是构造函数错误地说中心应该是 int 类型而不是 Point2D。

我不会用代码给你完整的答案,因为这显然是一项学校作业,我已经说过的内容应该对你有很大帮助。祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2014-12-07
    • 1970-01-01
    • 2022-06-12
    • 2013-10-22
    相关资源
    最近更新 更多