paint-brush
Java Constructor Interview Questionsby@bumblebee
2,989 reads
2,989 reads

Java Constructor Interview Questions

by Sonia JessicaApril 24th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Here we've listed the most commonly asked concepts on constructors in java that can help you ace your java interview.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Java Constructor Interview Questions
Sonia Jessica HackerNoon profile picture

What is a Constructor?

Constructor is the special method that is defined in the class with the name same as the class name. A java constructor is like a method having no return type. Constructors play the most important part in object initialization, and in this article, we have listed the constructor interview questions in java. We also have listed the importance of constructors in java, some constructor code snippets, etc that help you to answer the questions asked in your java interview from the constructor topic.

Why are constructors needed? Explain in detail

Suppose we have a class named Student. And we have instance variable name and roll_number.

class Student{
String name;
int rollNo;
}


Now if we create 1000 objects, then JVM will initialize these values with its default type Name = null and rollNo = 0. Identifying these individual objects is not possible and assigning values to each of the objects will increase code and that is a bad programming practice. So to avoid this kind of thing, constructors are used. So the purpose of the java constructor is to initialize the value to the instance variables of the class.

What are the different types of Constructors available in java? Define.

There are 3 different types of constructors available in java.

  • Default Constructor.
  • No-Argument Constructor.
  • Parameterized Constructor.


  • What is the default constructor in java? Default Constructor is the constructor that was created by the JVM during the runtime if no constructor is defined in the class. The main job of the default constructor is to initialize the values to the instances to their default type.


Default Constructor in java example -


class DefaultConstructor{

int id;

String name;

}

Now for this class, if we create the object then internally JVM creates a default constructor and assigns a default value.

DefaultConstructor df= new DefaultConstructor(); So now if we print the value then we will get -

Print = df.id = 0.df.name = null.


  • What is a No-Argument constructor in java? No-Argument Constructor is the constructor that the programmer will explicitly define to initialize the value to the instances.


    Example -


class NoArgConstuctor{ int a; int b;

//No Argument Constructor
NoArgConstuctor(){
a = 10;
b = 20;
}

}


  • What is parameterized constructor in java?

Parameterized constructor is the constructor in which the constructor accepts the parameter to initialize the instances. Example -

class ParameterizedConstuctor{
String name;
int age;
//Parameterized Constructor
ParameterizedConstuctor(String name, int age){
this.name = name;
this.age = age;
}
}


In the above code snippet, this keyword is their. And “this” keyword is used to refer to the current object.

What are the Rules for defining the constructor?

Several rules need to be followed for defining constructors. And those are

  • The name of the constructor must be the same as the class name.
  • There should be no return type of constructor applicable in java.
  • The only applicable modifiers for the constructors are -
    • a. public
    • b. default
    • c. protected
    • d. private
  • Constructors can accept any number of parameters.
  • Modifiers like - final, synchronized, static, and abstract are not allowed in the constructor.
  • The constructor doesn’t support the return statement inside its body.
  • Constructors can throw exceptions.
  • It is legal to use a throws clause with the constructor.
  • The constructor must not form recursion.

When can we use a private constructor?

In this case, when we don’t want to create objects of the particular class from outside, then we can use constructors as private. By declaring constructors as private, we are only allowed to create the objects within the class only. Singleton classes are a good example where private constructors are used.


What will be the default access modifier of the constructor if we don’t explicitly define it?

The access modifier of the constructor by default will always be the same as the class modifier. If the class is public, then the constructor will also be public. If the class will be private, then the constructor will also be private. And similarly applicable to another supported access modifier.

Identity the output of the below code snippet and state the reason.

class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class ScalerAcademy extends InterviewBit{
ScalerAcademy(){
System.out.println(" Welcome to Scaler Academy by InterviewBit");
}
}
class Main{
public static void main(String[] args) {
ScalerAcademy sc = new ScalerAcademy();
}
}


The above code will print - Welcome to InterviewBit. Welcome to Scaler Academy by InterviewBit.


It will print this output because in the constructor if we don’t specify the super() or this() keyword in the first line then, the JVM will automatically put this while execution. JVM does this because it is inheriting from the other class and the functionality will be implemented in the derived class also. So assigning the default values to the instances of the base class, JVM adds the super() keyword by default.


Consider the code below and state it is valid or invalid. And the reason for the answer.

class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class ScalerAcademy extends InterviewBit{
ScalerAcademy(){
this();
System.out.println(" Welcome to Scaler Academy by InterviewBit");
}
}
class Main{
public static void main(String[] args) {
ScalerAcademy sc = new ScalerAcademy();
}
}


The above code of invalid because we are again the same constructor in the Scaler Academy constructor. This will form a recursion in the constructor and that is not allowed in the constructor. So it will give a compile-time error saying - recursive constructor invocation.


Can we use 2 constructors in the same class in java?

Yes we can use any number of constructors in the same class with the condition that-

  • Parameters of the constructors must be different.
  • There should not be forming any kind of recursion in the constructor.
  • Example- Consider these 2 constructors of the same class InterviewBit.


InterviewBit(){
    this("Scaler"); // Calling parameterized constructor 
    System.out.println(" No Argument Constructor");
}
InterviewBit(String name){
    this(); // Calling no-arg constructor
    System.out.println(" Constructor with Parameters.");
}


This type of code is not allowed. Because it will form a recursion. No-arg constructor will call the parameterized constructor and parameterized will call the no-arg constructor.

Can we override a constructor in java?

No, the Constructor overloading concept is not applicable in java.

Can a constructor be final in java?

No Constructor cannot be final. It is because final keywords are used to stop overriding the method to the derived class. But in the constructor, the Overriding concept is not applicable so there is no need to write the final keyword. So if we write the final keyword in the constructor then we will get a compile-time error saying - required return type. Because the compiler treats it as the method.

Can a constructor be static in java?

No. the java constructor cannot be static. It is because static keywords are used when we want to make the member belong to the class, not for the object. But constructors are meant for initializing the objects. So the compiler will treat it as a method. So the error we get is- required return type.

Difference between super(), super and this(), this.

super() and this() are the constructor calls. It is only used to call the constructor of the parent class or current class. Whereas ‘super’ and ‘this’ is the keyword used for referring to the instance members of the own class or base class.


Example - Consider the below code-


class InterviewBit{
    String message = " Welcome to InterviewBit";
}
public class Scaler extends InterviewBit
{
    String message = " Welcome to Scaler Academy";
    public void printMethod(){
        //this will print the message variable of the current class.
        System.out.println(this.message);

        //this will print the message variable of Base class.
        System.out.println(super.message);
    }
	public static void main(String[] args) {
		Scaler sa = new Scaler();
		sa.printMethod();
	}
}


In the code snippet, ‘this.message’ will print the message “Welcome to Scaler Academy” and ‘super.message’ will print “Welcome to InterviewBit”. So this is how these both keywords are used to refer to the instance members of the base and derived classes.

What are destructors? Do we have a destructor in java?

Destructors are used to deallocate the memory acquired by the program. Or we can say that the memory required by the program during its runtime, destructor releases that memory, so that memory can be utilized by the other programs. And we don’t have the concept of destructor in java. Because the job of releasing the memory is handled by the garbage collection in java.

What is constructor chaining in java?

When one constructor is called from another constructor, then that can be said as constructor changing. Calling a constructor not necessary from others is not necessarily for the same class. It can be done for the parent class as well.

Example: Consider the below image.


For the above image, consider the below code for initialization of an object with the value values of these instance variables-

class EmployeeAddess{
    int pinCode;
    String address;
    String mobNo;
    EmployeeAddress(int pinCode, String address, String mobNo){
        this.pinCode = pinCodel
        this.address = address;
        this.mobNo = mobNo;
    }
}
class Employees extends EmployeeAddress{
    int ID;
    String name;
    String designation;
    String department;
    Employee(int ID, String name, String designation,String department,
                    int pinCode, String address, String mobNo){
        
        //Calling Constructor for Base class to initialize the object.
        //This can be a constructor chaining.
        super(pinCode, address, mobNo);
        this.ID = ID;
        this.name = name;
        this.designation = designation;
        this.department = department;
    }
}
public class Main{
    Employee emp = new Employee(101, "XYX", "SDE", "Cloud", 123456, "no 150, xys, xys, INDIA", "999999999");
}

In the above code, We are creating the object of Employee class with the Employee details and its address. An Employee address class is inherited by the Employee class. Now for instantiating the object value for the address, we are not explicitly assigning the values of employee address. Instead, we are using the Employee Address class constructor for doing that. And using the super(arguments) we are forming a chain of constructors to initialize the values. So this is what constructor chaining is all about.

Identify the output of the program and state the reason for your answer.

class InterviewBit{
void InterviewBit(){
System.out.println(" Java Constructor interview questions by InterviewBit");
}
int InterviewBit(int val){
System.out.println(" Java Constructor. And Value = "+val);
}
}
public class Main{
InterviewBit ib1 = new InterviewBit();
InterviewBit ib2 = new InterviewBit();
}

The above code will print nothing because InterviewBit() is not the constructor here. Void and int keywords are used so it becomes the method. So we are not calling the method. That's why it will not print anything. Because to execute methods, we need to explicitly call it by the object.

Write a java program to copy the values of the object to a new object using the constructor.

class Rectangle{
    int length;
    int breadth;
    Rectangle(int length, int breadth){
        this.length = length;
        this.breadth = breadth;
    }
    
    //Overloaded Constructor for copying the value of old Object to new object
    Rectangle(Rectangle obj){
        this.length = obj.length;
        this.breadth = obj.breadth;
    }
}
public class Main{
    Rectangle obj1 = new Rectangle(10, 5);
    
    //New Object of rectangle class will be created with the value from obj1. 
    Rectangle obj2 = new Rectangle(obj1);
}

In the above code, we have overloaded the constructor of the rectangle class. And that constructor will handle initializing the value to the new object from the old object received in the parameter.