avatarMpavani

Summary

This webpage provides an extensive list of Java constructor interview questions, covering topics such as constructor properties, initialization, and overloading, along with practical examples for understanding and usage in code.

Abstract

The article presents a comprehensive guide to Java constructors aimed at candidates preparing for core Java interviews. It addresses common queries about constructors, such as their ability to be final, static, abstract, or to throw exceptions. The author explains concepts like constructor chaining using this(), the absence of a return statement, and the provision of a default constructor by the compiler when none is explicitly defined. The piece also discusses the use of private constructors in design patterns, the differences between constructors and methods, and the capability of constructors to be overloaded. Additionally, it touches on the use of instance initializer blocks in anonymous inner classes and the significance of the @ConstructorProperties annotation, concluding with a clear distinction between super() and this() in the context of constructor invocation. The content is enriched with code snippets to illustrate each point, making it a valuable resource for understanding Java constructor behavior and best practices.

Opinions

  • The author emphasizes the importance of understanding constructor behavior as a critical skill for Java developers, particularly for those in the interview process.
  • The use of design patterns, such as Singleton, is encouraged for controlling object creation through private constructors.
  • The article suggests that frameworks like Jackson require the @ConstructorProperties annotation to map constructor parameters to bean properties for deserialization.
  • Constructors are seen as essential for object initialization, with their own set of rules distinct from methods, which are for defining object behavior.
  • The author advocates for the use of constructor overloading to provide flexibility in object creation with varying parameters, akin to method overloading.
  • The article implies that understanding the nuances between super() and this() is crucial for proper constructor chaining and inheritance.
  • The provision of a default constructor by the Java compiler in the absence of any user-defined constructors is highlighted as a key feature of the language.
  • Instance initializer blocks are presented as a workaround for the lack of constructors in anonymous inner classes.

Tricky Core Java Interview Questions Interviewer’s Favourite Topics(Constructors)

Hello All, In continuation to the series of my core java interview questions, today I’m sharing Constructor related questions that you can prepare for your interviews.

I’ve made it easy for you to refer interview questions as per the topics(Core Java, Microservices, Spring Boot, Design Patterns, AWS, etc.) and prepared lists below.

https://medium.com/me/lists

Can a constructor be final, static, or abstract? Why or why not?

  • A constructor cannot be final, static, or abstract.
  • Reason:
  • final: A final method cannot be overridden, but constructors are not inherited or overridden.
  • static: Constructors are associated with an instance of the class, while static is related to the class itself.
  • abstract: Abstract methods have no implementation, but constructors always have a concrete implementation.

Example:

class Test {
    // This will result in a compilation error:
    // final Test() {}
}

Can a constructor call another constructor in the same class?

  • Yes, using this() a constructor can call another constructor in the same class. This is called constructor chaining.
  • The this() call must be the first statement in the constructor.

Example:

class Example {
    int a, b;
    Example() {
        this(10, 20); // Calls parameterized constructor
        System.out.println("Default constructor");
    }
    Example(int a, int b) {
        this.a = a;
        this.b = b;
        System.out.println("Parameterized constructor: a = " + a + ", b = " + b);
    }
}
public class Main {
    public static void main(String[] args) {
        new Example();
    }
}

Output:

Parameterized constructor: a = 10, b = 20
Default constructor

Can a constructor throw exceptions?

  • Yes, a constructor can throw exceptions by declaring them in the throws clause.

Example:

class Example {
    Example() throws Exception {
        throw new Exception("Constructor exception");
    }
}
public class Main {
    public static void main(String[] args) {
        try {
            new Example();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Constructor exception

What happens if a constructor has a return statement?

  • A constructor cannot return a value (other than implicitly returning the current instance), but it can use return; to exit early.
  • If you try to return a value, the code will not compile.

Example:

class Example {
    Example() {
        System.out.println("Before return");
        if (true) return; // Exits the constructor
        System.out.println("After return"); // This will not execute
    }
}
public class Main {
    public static void main(String[] args) {
        new Example();
    }
}

Output:

Before return

What happens if a class does not define a constructor?

  • If a class does not define a constructor, the Java compiler provides a default constructor with no parameters.
  • If any constructor is explicitly defined, the default constructor is not generated.

Example:

class Example {
    // No explicit constructor, so the default constructor is provided
}
class ExampleWithConstructor {
    ExampleWithConstructor(String msg) {
        System.out.println("Parameterized constructor: " + msg);
    }
}
public class Main {
    public static void main(String[] args) {
        Example obj1 = new Example(); // Works
        // ExampleWithConstructor obj2 = new ExampleWithConstructor(); // Error: No default constructor
    }
}

Can a constructor be private? When is it used?

  • Yes, a constructor can be private. It is commonly used in:
  1. Singleton Pattern: Restrict object creation to a single instance.
  2. Factory Methods: To control instance creation.

Example:

Singleton Pattern:

class Singleton {
    private static Singleton instance;
    private Singleton() {
        System.out.println("Private constructor called");
    }
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
public class Main {
    public static void main(String[] args) {
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
        System.out.println(obj1 == obj2); // true, same instance
    }
}

What is the difference between a constructor and a method?

Can a constructor be overloaded?

  • Yes, constructors can be overloaded by defining multiple constructors with different parameter lists.

Example:

class OverloadExample {
    OverloadExample() {
        System.out.println("Default constructor");
    }
    OverloadExample(int x) {
        System.out.println("Constructor with one parameter: " + x);
    }
    OverloadExample(int x, int y) {
        System.out.println("Constructor with two parameters: " + x + ", " + y);
    }
}
public class Main {
    public static void main(String[] args) {
        new OverloadExample();
        new OverloadExample(10);
        new OverloadExample(10, 20);
    }
}

What happens if you call a non-existent constructor?

  • If you try to call a constructor that doesn’t exist (e.g., missing parameters), the code will fail to compile.

Example:

class Example {
    Example(int x) {
        System.out.println("Constructor with parameter: " + x);
    }
}
public class Main {
    public static void main(String[] args) {
        // new Example(); // Compilation error: No default constructor
    }
}

Can a subclass inherit a superclass constructor?

  • No, constructors are not inherited, but a subclass can invoke a superclass constructor using super().

Example:

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}
class Child extends Parent {
    Child() {
        super(); // Calls Parent constructor
        System.out.println("Child constructor");
    }
}
public class Main {
    public static void main(String[] args) {
        new Child();
    }
}

Output:

Parent constructor
Child constructor

How are constructors used in anonymous inner classes?

Anonymous inner classes cannot have constructors because they do not have a name. Instead, an instance initializer block can be used.

Example:

abstract class Greeting {
    abstract void sayHello();
}
public class Main {
    public static void main(String[] args) {
        Greeting g = new Greeting() {
            { // Instance initializer block
                System.out.println("Anonymous class initialized");
            }
            void sayHello() {
                System.out.println("Hello!");
            }
        };
        g.sayHello();
    }
}

How does the @ConstructorProperties annotation work?

@ConstructorProperties maps constructor parameters to the properties of a bean, enabling frameworks like Jackson to deserialize objects.

Example:

import java.beans.ConstructorProperties;
class Person {
    private final String name;
    private final int age;
    @ConstructorProperties({"name", "age"})
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

What is the difference between super() and this() in constructors?

  • super() calls a constructor from the parent class.
  • this() calls another constructor from the same class.

Example:

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}
class Child extends Parent {
    Child() {
        this("Child"); // Calls another constructor in the same class
    }
    Child(String name) {
        super(); // Calls the parent constructor
        System.out.println(name + " Constructor");
    }
}

Explain constructor overloading vs method overloading in Java.

class OverloadingExample {
    // Constructor overloading
    OverloadingExample() {}
    OverloadingExample(int x) {}

    // Method overloading
    void method() {}
    void method(int x) {}
}

What are constructors in Java, and how do they differ from methods?

A constructor is a special method used to initialize objects. It is called when an object is created. Key differences:

  • Constructors have the same name as the class and no return type, not even void.
  • Methods define behaviors, while constructors initialize an object’s state.
class Example {
    int value;

    // Constructor
    Example(int value) {
        this.value = value;
    }

    // Method
    void display() {
        System.out.println("Value: " + value);
    }
}

Stackademic 🎓

Thank you for reading until the end. Before you go:

Java
Programming
Technology
Interview
Software Development
Recommended from ReadMedium