Constructors (Lesson-29)

A constructor is a special method in a class which is called automatically when an object of that class is created. It is used to initialize the newly created object.
A constructor:

  • is a method
  • has exactly the same name as the class
  • has no return type
  • is not static

Constructor can be used to provide initial values for the attributes of the object.
Let’s consider the Car class with color as an attribute. The constructor will set the default color of the car to green.

public class Car {
    String color;

A constructor does not have a return type but it can take parameters. Let’s modify the constructor of the Car class to take color as the parameter and set it.

public class Car {
    String color;
    Car(String c){

This parameter is passed at the time of creation of object. For example, to create an object of our new Car class, we will use:

Car tesla=new Car("blue");

A class can have more than one constructors but all the constructors should use different parameters. For example, consider the Car class again with two constructors. One takes no parameter and other takes a String parameter.
You already learnt that constructor is executed when an object of the class is created. If there are more than one constructors, only one of them is executed. It depends on the parameters given at the time of creation of object. For example, in our above Car class, if no parameter is passed at the time of creation, the first constructors will execute and the color of the car will be set to green. However, if a String parameter is passed, the color of the class will be set to what is passed as the parameter.
Note: If you do not write a constructor in a class, java automatically provides a constructor which takes no parameters and does nothing.

If an initial value of an attribute is set by the constructor, it can be changed later:

Practice Corner:
  • Create a bank account class with int balance as attribute. One takes no parameter and initializes the balance to zero. The other constructor will take initial balance as parameter and set it.

2 thoughts on “Constructors (Lesson-29)”

Leave a Comment