Java Tutorial Series - Constructor

We are coming up with Java series for our blog and will be covering new concepts as much as possible. The very first concept which we would like to cover is a constructor in Java, it is a very important topic and is often covered in a lot of programming interview questions. Input and output questions are derived from this topic. Be prepared with Constructor questions before appearing for any written interview.

What is Constructor in Java?

The constructor is like any other method in Java with the same name as of class name. It is called when an object is created using new() keyword. Java compiler creates a default constructor if the default class doesn't have any. It is called as a constructor because it constructs the value at the time of object creation.

The rules for Constructor
  • The constructor name is the same as that of the class name.
  • A constructor must have no explicit return type
  • A constructor cannot be declared as abstract, static, final and synchronized.
  • A constructor can be declared as private.
There are 2 types of constructors -
  • Default constructor- which doesn't have any parameters
  • Parameterized constructor
Default constructor -
For integer, 0 value is passed even if no constructor is declared and for String Null is passed.

Parameterized Constructor -
In the parameterized constructor, we pass the parameters while creating an object.

Constructor Overloading in Java -

Just like method overloading, a constructor can also be overloaded with different parameters.

Difference between Constructor and Method in Java -
One of the common interview questions that need to be covered.




Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD