Class Constructor in Java

(Last Updated On: February 26, 2019)

Learn how to create a class constructor in java programs with example and when constructors get called and about its important points.

What is class constructor in java

In brief,

In java, constructor of a class is a special method that has same name as the class name and it is automatically called when you create an object of the class. Constructor is used to initialize the object of the class at the time of object creation. There can be multiple constructors in a class having different parameters. Constructors does not have return type as methods and cannot be called explicitly.

Let’s get in detail with class constructor in java in simple language step by step.

NOTE:

[I have divided the constructor lesson in 4 posts for your better and easy understanding. First, we will understand simple constructor first i.e. how to write in a class and how the constructor gets called when we create an object of the class. Then we will understand parametrized constructor, writing multiple constructors in a class and then how to initialize object of the class. Links for the posts will be provided later in this post]

Lets start simple.

Suppose there is a class Car , then its constructor will be as below seen in example with same name of the class i.e. public Car(){}. It is similar to a method but does not have return type.

 

In above class constructor example, when we create an object of the class Car, lets say, Maruti , as, “Car maruti = new Car();” then constructor will be called automatically. [ You can read more on how to create an object of a class in java here.]

You need to remember the Golden Rule given below.

Golden Rule: “Create an object of a class, the class constructor will get called automatically”

Lets dive deeper with a complete java code example.

 

Class Constructor and its Calling Example in java

In below java source code example, a Car class is there containing a constructor “public Car()” . When we create an object of the class Car, lets say, Maruti , as, “Car maruti = new Car();” then constructor will be called automatically.

Similarly, when we create object Honda of the class Car, then again constructor will be called. Means, As many times as you create an object of the class using new keyword, the constructor will get called every time automatically / implicitly.

Constructor Calling Java Example

 

Output
Constructor…
Car is running…
Constructor…
Car is running…