08.02. Constructor Overview

Constructor Overview

  • Eclipse: Oxygen
  • Java: 1.8

Constructor Introduction:

In Java, Constructor is a special method, which is invoked when an object of the class is created. It is used to initializing the class variables.

There are some rules for construction creation:

  • A constructor always has the same name as the class name.
  • A constructor is a special method that does not has any return type

The constructor is of two types

  • Default constructor
  • Parameterized constructor

Default Constructor – If you do not have any constructor in your class, Java compiler adds a default constructor to the class during compilation.

In the following example, we did not use the object of the class to initialize the variable, rather all the variables have been initialized using a constructor.

Default constructor example

When “Car” is instantiated within another “Hello” class, the default constructor of Car class gets invoked and initialized all the variables.

Output

car is running

Parameterized Constructor – Constructor which accepts the parameters is called the parameterized constructor. By using the parameterized constructor, you can provide values to variables during instantiating the class.

You can generate parameterized constructor from the toolbar menu:

Source >> Generate Constructor using fields

Select the field or methods for which you want to generate the parameterized constructor.

Parameterized constructor example

In this program Value to the variables is provided during object creation of the class.

Output

car is running

In Java, when you do not have any constructor in the class, so during execution Java compiler adds one constructor in the class, it is called as default constructor.

The default constructor does not have any parameters. The default constructor is used to providing the default value to instance variables.

Default Constructor added by JVM

In the following example, In Smartphone class we do not write any constructor so JVM will add a default constructor in the class and properties of the Smartphone class will be initialized using this default constructor.

As soon as we create the object of Smartphone class using the new keyword, the default constructor of the class is invoked.

Output:

Samsung

Default constructor added by User

In the following example, we will add a default constructor in Smartphone class.

Again we create the object of Smartphone class using the new keyword, the default constructor of the class is invoked.

Output:

Nokia

Note: If you add a parameterized constructor in the class then no default constructor will be added by JVM.

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments