Constructor in Java

Constructor in Java is used to initialize the Object of the class. In this tutorial, you will learn about the importance and uses of Java Constructor.

  • Java Constructor is used to initializing the objects.
  • Constructor declaration looks like method declaration. It must have the same name as that of the class and have no return type.
  • Constructors can be classified into two types, default constructors, and parameterized constructors.
  • If we don’t define a constructor in our program, then the compiler creates a default constructor. Default constructors do not contain any parameters.

 

Define the Constructor

A constructor must be the same name as that of the class. The constructor doesn’t have the return type. in below example NewClass() is the constructor.

Using the class name for the constructor signals to the Java compiler that this is a constructor.

 

Video Tutorial of Automation Testing:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

 

Default (No- Argument) Constructor

If you don’t define the constructor for the class then Java compiler will insert a default or no-argument constructor for you. If we define the constructor then Java compiler doesn’t insert the default constructor.

 

Parameterized Constructor

Parameterized constructors are required to pass parameters to objects. If you create parameterized constructor then the compiler doesn’t create the default constructor.

Output:

I am in parameterized constructor.
The parameter value is : Selenium Bix

 

Private Constructor

The private constructor is useful in Java singleton class. We can make constructor as private. So that we can’t create the object outside of the class. This pattern helps us to keep only one instance of the class at a time.

 

Constructor vs Method

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

0 Comment

Leave a Reply