Constructors

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A Constructor is a special block of code that is called when an object is instantiated.
  • It is used to initialize the state of the object.
  • It must have the exact same name as the class and cannot have a return type (not even void).

Concept

When you use the new keyword, at least one constructor is invoked.

  1. Default Constructor: If you do not provide any constructors in your class, the Java compiler automatically inserts a no-argument constructor that does nothing (other than calling the superclass constructor).
  2. Parameterized Constructor: A constructor that takes arguments, allowing you to initialize an object with specific data at the moment of creation.
  3. Constructor Overloading: Like methods, you can have multiple constructors in a class as long as their parameter lists are different.

Examples

class Person {
    String name;
    int age;
    
    // 1. No-Argument Constructor
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }
    
    // 2. Parameterized Constructor (Overloaded)
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class ConstructorExample {
    public static void main(String[] args) {
        // Calls the no-arg constructor
        Person p1 = new Person(); 
        
        // Calls the parameterized constructor
        Person p2 = new Person("Alice", 28); 
    }
}

Interview Questions

Q: What happens if you define a parameterized constructor but no default constructor, and try to use new MyClass()?
A: You will get a compilation error. The Java compiler only provides an automatic default (no-arg) constructor if you provide zero constructors. The moment you define a parameterized constructor, the compiler steps back. If you still want to be able to create an object without passing arguments, you must explicitly write a no-argument constructor.

Q: Can a constructor be final, static, or abstract?
A: No.

  • A constructor cannot be abstract because it must be executed when the object is created.
  • It cannot be static because it is tied to object instantiation (instance creation), whereas static means it belongs to the class.
  • It cannot be final because constructors are not inherited, so there is no concept of overriding them, making final meaningless.