Can you declare an instance variable as a parameter in a constructor?

后端 未结 3 455
面向向阳花
面向向阳花 2021-01-24 03:41

Would this work?

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

I am just trying to figure out the constructor. If it is called like a method t

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 04:27

    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.

    For example in this way:

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

    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.

提交回复
热议问题