JavaRush /Java Blog /Random EN /Coffee break #123. Java Constructor - Technical Interview...

Coffee break #123. Java Constructor - Technical Interview Questions and Answers

Published in the Random EN group
Source: Hackenoon

What is Constructor?

Constructor is a special method defined in a class with the same name as the class name. A Java constructor is like a method that does not have a return type. Coffee break #123.  Java Constructor - Technical Interview Questions and Answers - 1Constructors play the most important role in the initialization of objects and in this article, we will list sample interview questions that cover constructors in Java. You will also learn about the importance of constructors in Java, see code examples and other important details that will help you answer questions about Java constructors in an interview.

Why are constructors needed? Explain in detail

Let's say we have a class named Student . And we have the instance variable name and roll_number .
class Student{
String name;
int rollNo;
}
Now, if we create 1000 objects, then the 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 the amount of code, which is considered bad programming practice. Therefore, to avoid this, constructors are used. That is, the purpose of a constructor in Java is to initialize the value of class instance variables.

What types of constructors are there in Java?

There are three different types of constructors in Java:
  • Default Constructor
  • No-Argument Constructor
  • Parameterized Constructor

What is Default Constructor in Java?

A Default Constructor is a constructor created by the JVM at runtime if no constructor is defined in the class. The main job of the default constructor is to initialize the values ​​of instances according to their default type. Example default constructor in Java:
class DefaultConstructor{
int id;
String name;
}
Now for this class, if we create an object, then inside the JVM there will be a default constructor which is given a default value.
DefaultConstructor df= new DefaultConstructor();
Now if we print the value we will get:
Print = df.id = 0.df.name = null.

What is a No-Argument Constructor?

A no-argument constructor is a constructor that can be explicitly defined to initialize the value of instances. For example:
class NoArgConstuctor{ int a; int b;

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

}

What is a Parameterized Constructor?

A parameterized constructor is a constructor that accepts a parameter to initialize instances. For example:
class ParameterizedConstuctor{
String name;
int age;
//Parameterized Constructor
ParameterizedConstuctor(String name, int age){
this.name = name;
this.age = age;
}
}

What are the rules for defining a constructor?

To define constructors, you must follow several rules:
  • The constructor name must match the class name.

  • There should not be a constructor return type in Java.

  • The only applicable modifiers for constructors are:

    • public
    • default
    • protected
    • private
  • Constructors can take any number of parameters.

  • The modifiers final, synchronized, static and abstract are not allowed in a constructor.

  • The constructor does not support a return statement within its body.

  • There can be exceptions with a throw statement in the constructor .

  • It is acceptable to use a throws clause with a constructor.

  • The constructor should not generate recursion.

When can we use a private constructor?

If we do not want to create objects of a certain class from the outside, we can use closed or private constructors. By declaring constructors private, we can create objects only within the class. Singleton classes are a good example of the use of private constructors.

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

The default constructor access modifier will always be the same as the class modifier. If the class is public, then the constructor will also be public. If the class is private, then the constructor will also be private. The same will happen with other access modifiers.

Write the output of the below code snippet and explain

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.
We'll get this output because if we don't include the super() or this() keyword in the constructor on the first line, the JVM will automatically put it in at runtime. The JVM does this because it inherits from another class and its functionality will also be implemented in the derived class. Thus, when assigning default values ​​to base class instances, the JVM adds the super() keyword by default .

Review the code and indicate whether it is valid or invalid. Explain the reason

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 is invalid because it is the same constructor inside the Scaler Academy constructor . This creates recursion in the constructor, which is not allowed. Accordingly, we will receive a compile-time error associated with the call to the recursive constructor.

Can we use two constructors in one class in Java?

Yes, we can use any number of constructors in one class, subject to two conditions:
  • The constructor parameters must be different.
  • There should be no recursion in the constructor.
Example. Consider two constructors of the same InterviewBit class :
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 code is not valid because it will create a recursion. A constructor with no arguments will call a constructor with parameters, and a constructor with parameters will call a constructor with no arguments.

Can we override a constructor in Java?

No, the concept of constructor overloading is not applicable in Java.

Can a constructor be final in Java?

No constructor can be final. This is because the final keywords are used to stop overriding a method in a derived class. But in a constructor, the concept of overriding does not apply, so there is no need to write the final keyword . If we write the final keyword in the constructor, we will get a compile-time error called required return type because the compiler treats it as a method.

Can a constructor be static in Java?

No, a Java constructor cannot be static. This is because the static keywords are used when we want a member to belong to a class rather than an object. But constructors are meant to initialize objects, so the compiler will treat it as a method. We'll get a required return type error .

Describe the difference between super(), super and this(), this

super() and this() are constructor calls. It is only used to call the constructor of the parent class or the current class. Note that “super” and “this” are keywords used to designate members of an instance of its own class or a base class. Consider the code below:
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 this code snippet, this.message will print the message “ Welcome to Scaler Academy ” and super.message will print “ Welcome to InterviewBit ”. This is how these two keywords are used to refer to member instances of the base and derived classes.

What are destructors? Does a destructor exist in Java?

Destructors are used to free memory acquired by a program. For example, if memory is needed by a program during its execution, the destructor frees that memory so that other programs can use it. There is no concept of a destructor in Java because the work of freeing memory in Java is handled by the garbage collector.

What is constructor chaining in Java?

When one constructor is called from another constructor, this can be called constructor chaining. The constructor call does not have to be made on the same class. This can be done for the parent class as well. For an example, consider the image below. Coffee break #123.  Java Constructor - Technical Interview Questions and Answers - 2Next, we can look at the code to initialize the 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 an Employee class object with the employee details and his address. The Employee address class is inherited by the Employee class . Now, to instantiate an object value for an address, we don't assign an explicit value to the employee's address. Instead, we use the constructor of the Employee Address class to do this . And with the help of super(arguments) we form a chain of constructors to initialize the values. That's what a constructor chain is.

Determine the program output from the code and explain 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 not print anything because InterviewBit() is not a constructor here. Since the Void and int keywords are used , it becomes a method. Therefore we don't call the method. We won't get any output because to execute the method we need to explicitly call it on the object.

Write a program to copy the values ​​of an object into a new object using a 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);
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION