Java Constructors: A Comprehensive Guide with Examples

This Java tutorial provides a comprehensive guide to constructors, explaining their purpose, different types (default, parameterized, copy), and how to implement copy constructors in Java. Learn how constructors are essential for object initialization and understand best practices for their usage.



Java Constructor Interview Questions

What is a Constructor?

Question 1: What is a Constructor?

A constructor in Java is a special method used to initialize objects of a class. It's automatically called when you create a new object using the `new` keyword. Constructors have the same name as the class and don't have a return type.

Types of Constructors

Question 2: Types of Constructors

Two main types:

  • Default Constructor (Non-parameterized): No parameters; provides default initialization.
  • Parameterized Constructor: Accepts parameters; allows for customized initialization.
Example: Default Constructor

class Employee {
    int id;
    String name;
    Employee() {} // Default constructor
}
Example: Parameterized Constructor

class Employee {
    int id;
    String name;
    Employee(int i, String n) {
        id = i;
        name = n;
    }
}

Copy Constructor in Java

Question 3: Copy Constructor in Java

Java doesn't have a dedicated copy constructor like C++. However, you can achieve similar functionality by creating a new object and copying the values from an existing object. Methods include using a constructor that takes another object as a parameter, assigning values directly, or using the `clone()` method.

Copying Objects

Question 4: Copying Object Values

Java Code

class ConstructorDemo {
    int id;
    String name;
    ConstructorDemo(int i, String n) {
        id = i;
        name = n;
    }
    ConstructorDemo(ConstructorDemo c) {
        id = c.id;
        name = c.name;
    }
    void display() {
        System.out.println(id + " " + name);
    }
    public static void main(String args[]) {
        ConstructorDemo c1 = new ConstructorDemo(100, "Joy");
        ConstructorDemo c2 = new ConstructorDemo(c1);
        c1.display(); // Output: 100 Joy
        c2.display(); // Output: 100 Joy
    }
}

Calling Subclass Constructors from Superclass

Question 5: Calling Subclass Constructor from Superclass

You cannot directly call a subclass constructor from a superclass constructor in Java. However, you can call a superclass constructor from a subclass constructor using the `super()` keyword.

Constructors in Interfaces

Question 6: Constructors in Interfaces

Interfaces in Java cannot have constructors.

Constructor Chaining

Question 7: Constructor Chaining

Constructor chaining is when one constructor calls another constructor within the same class (using `this()`) or in a superclass (using `super()`). This is typically done to reduce code duplication.

Java Code

class TestSuper {
    public TestSuper(int i) {
        System.out.println("Super Class Constructor"); // Output: Super Class Constructor
    }
}
class TestSub extends TestSuper {
    public TestSub() {
        this(10); 
    }
    public TestSub(int i) {
        super(i); 
    }
}
public class Main{
    public static void main(String[] args){
        new TestSub();
    }
}

Return Types in Constructors

Question 8: Return Type in Constructor

Constructors cannot have a return type. If you specify a return type, it becomes a regular method, not a constructor. The compiler will issue a warning.

Java Code (Example with warning)

public class TestConstructor {
    int TestConstructor() {
        return 0; // This will cause a compiler warning
    }
}

Private Constructors

Question 9: Private Constructors

A private constructor prevents object creation from outside the class. It's often used in singleton design patterns or when you want to control instantiation of the class.

Java Code

class SingletonDemo {
    private SingletonDemo() {
        System.out.println("In a private constructor"); // Output: In a private constructor
    }
    public static SingletonDemo getObject() {
        if (ref == null) ref = new SingletonDemo();
        return ref;
    }
    private static SingletonDemo ref;
}
public class PrivateConstructor {
    public static void main(String args[]) {
        SingletonDemo sObj = SingletonDemo.getObject();
    }
}

Static Constructors

Question 10: Static Constructors

Constructors cannot be declared as `static` in Java because constructors are always called on an object instance; static methods belong to the class itself, not to any specific object instance.

Final Constructors

Question 11: Final Constructors

You cannot declare a constructor as `final` in Java. The compiler will report an error.

Protected Constructors

Question 13: Protected Constructors

A protected constructor can only be accessed within the same package or by subclasses. It is typically used to control the instantiation of a class.

Constructor Naming

Question 14: Why Constructor Name is Similar to Class Name

The constructor's name must match the class name to allow the JVM to identify the constructor correctly during object creation.

Return Type in Constructors

Question 15: Why No Return Type in Constructor

Constructors don't have a return type. Specifying a return type makes it a regular method, not a constructor.