Skip to content

Constructors

  • Lesson
  • 2 min read
  • 4 of 5 in this chapter

What is a constructor?

A constructor is a special type of method that is used to initialize objects.

The constructor is called when we create an object, and it sets the values of the object attributes.

And since it's a method, we can overload it with various parameters.

Add this to your Vehicle class:

Java
public Vehicle(String type, String color, String model, boolean isElectric, int cost) {
  this.type = type;
  this.color = color;
  this.model = model;
  this.isElectric = isElectric;
  this.cost = cost;
}

This is our first constructor. It has all of the same parameters as the object attributes, so we can map them.

Did you notice the this? this specifies that we are talking about the object attributes, not the parameters.

In an earlier lesson, we didn't use this. We named our parameters differently. You only need to use this when you have variables/parameters of the same name but in different scopes. We can only access the parameters of the constructor within the constructor. However, we can access our object attributes anywhere.

This is a very basic constructor, so let's also set a default constructor. This is what will happen if we don't specify any parameters when we create the object.

Java
public Vehicle() {
  type = "Car";
  color = "Red";
  model = "Tesla Model 3";
  this.isElectric = true;
  this.cost = 35000;
}

Changing Wheels

We know we set the value of wheels to 4. But we can change them, and also set other variables based on wheels.

Here's an example of a constructor that does this:

Java
public Vehicle(int wheels, String color, String model, boolean isElectric, int cost) {
  if(wheels == 2) {
    type = "Motorcycle";
  } else {
    type = "Other";
  }

  this.color = color;
  this.model = model;
  this.isElectric = isElectric;
  this.cost = cost;
}

Calling the Objects

Now that we have our object attributes and constructor set up, we can create new instances of the Vehicle class.

In Main.java, let's create three different Vehicle objects.

Java

Vehicle tesla = new Vehicle();
Vehicle motorcycle = new Vehicle(2, "Blue", "Harley-Davidson LiveWire", true, 30000);
Vehicle malibu = new Vehicle("Sedan", "Silver", "Chevy Malibu", false, 23000);

And that's it! We created three different objects with their own unique attributes, all based upon the Vehicle class.

In the next lesson, we will be creating various methods, including setter/getter and toString().