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

微笑、不失礼 提交于 2019-12-02 04:02:35

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.

Constructors are used as a way to instantiate a new Instance of that Object. They don't have to have any instance variable inputs. Instance variables are declared so multiple methods within a particular class can utilize them.

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

In the example above, the constructor didn't set the instance variables, the init() method did. This was so that useInstance() could use those variables.

You are probably not understanding the correct use of Constructors.

Constructor

A constructor is used in the creation of an object that is an instance of a class. Typically it performs operations required to initialize the class before methods are invoked or fields are accessed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!