你能否将一个实例变量声明为构造函数中的参数? [英] Can you declare an instance variable as a parameter in a constructor?

查看:136
本文介绍了你能否将一个实例变量声明为构造函数中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会有效吗?

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

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

I am just trying to figure out the constructor. If it is called like a method then I thought it would work similar to a method. You can create local variables in a method that are used when that method is called so I don't see why instance variables have to be declared before constructors can use them.

推荐答案

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

In your example speed and weight are not instance variables because their scope is limited to the constructor. You declare them outside in order to make them visible throughout the whole class (i.e. throughout objects of this class). The constructor has the purpose of initialising them.

例如以这种方式:

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;
    }
}

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

Here sp and w are parameters which are used to set the initial value of the instance variables. They only exist during the execution of the constructor and are not accessible in any other method.

这篇关于你能否将一个实例变量声明为构造函数中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆