你能否将一个实例变量声明为构造函数中的参数?

这会有用吗?

class Cars{ Cars(int speed, int weight) } 

我只想弄清楚构造函数。 如果它像方法一样调用,那么我认为它的工作方式类似于方法。 您可以在调用该方法时使用的方法中创建局部变量,因此我不明白为什么必须在构造函数可以使用它们之前声明实例变量。

在您的示例中,速度和权重不是实例变量,因为它们的范围仅限于构造函数。 你在外面声明它们是为了使它们在整个类中可见(即在这个类的整个对象中)。 构造函数的目的是初始化它们。

例如这样:

 public class Car { // visible inside whole class private int speed; private int weight; // constructor parameters are only visible inside the constructor itself public Car(int sp, int w) { speed = sp; weight = w; } public int getSpeed() { // only 'speed' and 'weight' are usable here because 'sp' and 'w' are limited to the constructor block return speed; } } 

这里spw是用于设置实例变量初始值的参数。 它们仅在构造函数的执行期间存在,并且在任何其他方法中都不可访问。

构造函数用作实例化该Object的新实例的方法。 它们不必具有任何实例变量输入。 声明了实例变量,因此特定类中的多个方法可以使用它们。

 public class Foo{ String x; int y; Foo(){ //instance variables are not set therefore will have default values } void init(String x, int y){ //random method that initializes instance variables this.x = x; this.y = y; } void useInstance(){ System.out.println(x+y); } } 

在上面的例子中,构造函数没有设置实例变量,init()方法也没有。 这是因为useInstance()可以使用这些变量。

 You are probably not understanding the correct use of Constructors. 

构造函数

构造函数用于创建作为类实例的对象。 通常,它会在调用方法或访问字段之前执行初始化类所需的操作。