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

后端 未结 3 451
面向向阳花
面向向阳花 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条回答
  •  生来不讨喜
    2021-01-24 04:21

    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.

提交回复
热议问题