【问题标题】:Definition of variables/fields type within a constructor, how is it done?在构造函数中定义变量/字段类型,它是如何完成的?
【发布时间】:2010-04-20 19:44:14
【问题描述】:

我刚刚看了 Suns Java 教程,发现了一些让我完全困惑的东西: 给定以下示例:

public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;

}

为什么不需要定义变量(字段?)齿轮、节奏和速度的类型? 我会这样写:

public Bicycle(int startCadence, int startSpeed, int startGear) {
int gear = startGear;
int cadence = startCadence;
int speed = startSpeed;

}

实际的区别是什么?

【问题讨论】:

  • 最后一个替代方法实例化方法变量。这些变量在构造函数被调用后消失,而在第一个替代方案中使用的类变量是给定构造函数启动的对象的一部分。

标签: java constructor field


【解决方案1】:

您的代码将声明 局部变量 - 当构造函数完成时,它们实际上会消失。让我们看看the code 的更多上下文:

// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

现在您可以看到声明 - 它们是在构造函数之外声明的,因为它们是实例字段,而不是局部变量。它们构成Bicycle 类的每个实例的数据。

【讨论】:

    【解决方案2】:

    很可能这些字段已经在类中较早地定义,在构造函数之前。我们能看到全班吗?

    构造函数只是类的一部分,一般不包含实例变量的初始化。您通常会在类的顶部看到那些定义。

    【讨论】:

    【解决方案3】:

    它们被定义为类变量,并得到一个隐含的 this 附加。为了更清楚,它可以阅读

    公共自行车(int startCadence,int startSpeed,int startGear){ this.gear = startGear; this.cadence = startCadence; this.speed = startSpeed; }

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 1970-01-01
      • 2020-10-18
      • 2023-03-03
      • 1970-01-01
      • 2012-03-09
      • 2019-05-25
      • 2011-10-31
      • 2022-06-15
      相关资源
      最近更新 更多