Classes: Constructor Parameters - Explanation help


#1

Hello, please forgive the noob question but I am trying to understand the topic and maybe I am trying to make this too simple but looking at the example below: -

  1. So we have created a variable for our Car class (int modelYear)
  2. We then create a parameter (int year)
  3. Then we are saying modelYear = year

I am confused aren’t we creating 2 integers that are doing the same thing modelYear and year? Why do we create them both and refernece one to the other? I hope this makes sense, just trying to wrap my head around it all

class Car {

    //Use instance variables to model our Car class after a real-life car
    int modelYear;

    public Car(int year) {

        modelYear = year;
    }
}

#2

lets say we added another method, lets name this method carInformation and this method prints:

The car was build in 2008

now, we don’t want to specify 2008 every time when we call carInformation method. We just want to provide this information once when we create a class instance.

this is why we use a constructor (public Car), to make an instance variable which we can access in other methods. Quite useful. You will see in the next few exercises.


#3

Not realy, The int year is not realy created. this is used so the constructor knows an int has to be given when you create a new car.

In the example below i have commented what happens in this piece of code.

class Car {

    //Use instance variables to model our Car class after a real-life car
    int modelYear;     // initialize a variable that contains the modelyear

    public Car(int year) {    // wenn creating a new car make sure a modelyear has been given.

        modelYear = year;    // set the modelyear of this object to the year given at creation.
    }
}

A new car could be created with this code

Car volvo = new Car(1997) ;  // create a new Car with the modelyear "1997"

Now if you try to create a car this way:

Car volvo = new Car();  // create a new car without a modelyear

It will throw an error at you because you specificly said that the constructor need an integer “year”

To call it short: Car(int year) is saying a integer is needed wen creating a new object. it does not create a new variable.