DEV Community

Cover image for Java Interview - constructor
Yiğit Erkal
Yiğit Erkal

Posted on

Java Interview - constructor

Let's talk about the constructors in Java and what can be asked during the Java interview related to constructors?

What is Constructor in Java?

We use constructors to initialize all variables in the class when an object is created. As and when an object is created it is initialized automatically with the help of constructor in java.

We have two types of constructors:
1) Default Constructor
2 Parameterized Constructor

public className(){}
public className(parameters list){}
Enter fullscreen mode Exit fullscreen mode

How to Call One Constructor From the Other Constructor?

With in the same class if we want to call one constructor from other we use this() method. Based on the number of parameters we pass appropriate this() method is called.

Restrictions for using this method:
1) This must be the first statement in the constructor
2) We cannot use two this() methods in the constructor

Difference Between This() and Super() in Java?

this() is used to access one constructor from another with in the same class while super() is used to access superclass constructor. Either this() or super() exists it must be the first statement in the constructor.

Can We Override Constructors in Java?

Only methods can be overridden in java. Constructors can’t be inherited in java. So, there is no point of overriding constructors in java.

Top comments (0)