Constructors

Object initialization

Interview Relevant: Constructor chaining questions
6 min read

Constructors in Java

A constructor is a special method that initializes an object when it's created. It has the same name as the class and no return type.

Constructor Rules

  • Name must match class name exactly
  • No return type (not even void)
  • Called automatically when new is used
  • Can be overloaded (multiple constructors)
  • Cannot be abstract, final, static, or synchronized

🔑 Default Constructor: If you don't define any constructor, Java provides a no-arg constructor. But if you define ANY constructor, the default is NOT provided!

💡 Constructor Chaining: Use this() to call another constructor in same class, super() to call parent constructor.

Code Examples

Default and no-arg constructors

java
1// Default Constructor (provided by Java if no constructor defined)
2public class DefaultExample {
3    int value;
4    // Java provides: public DefaultExample() { }
5}
6
7// No-arg Constructor (explicit)
8public class Car {
9    String brand;
10    int year;
11    
12    // No-arg constructor
13    public Car() {
14        brand = "Unknown";
15        year = 2000;
16        System.out.println("Car created with defaults");
17    }
18}
19
20// Usage
21Car car = new Car();  // Prints: Car created with defaults
22System.out.println(car.brand);  // Unknown
23System.out.println(car.year);   // 2000

Parameterized constructors

java
1// Parameterized Constructors
2public class Person {
3    private String name;
4    private int age;
5    
6    // Parameterized constructor
7    public Person(String name, int age) {
8        this.name = name;  // 'this' distinguishes field from parameter
9        this.age = age;
10    }
11    
12    // Another parameterized constructor
13    public Person(String name) {
14        this.name = name;
15        this.age = 0;  // Default age
16    }
17    
18    public void display() {
19        System.out.println(name + ", " + age);
20    }
21}
22
23// Usage
24Person p1 = new Person("Alice", 25);  // Uses first constructor
25Person p2 = new Person("Bob");        // Uses second constructor
26
27p1.display();  // Alice, 25
28p2.display();  // Bob, 0

Constructor overloading and chaining with this()

java
1// Constructor Overloading and Chaining
2public class Rectangle {
3    private int width;
4    private int height;
5    
6    // No-arg constructor - calls another constructor
7    public Rectangle() {
8        this(1, 1);  // Constructor chaining with this()
9    }
10    
11    // Constructor with one parameter (square)
12    public Rectangle(int side) {
13        this(side, side);  // Calls the two-arg constructor
14    }
15    
16    // Constructor with all parameters
17    public Rectangle(int width, int height) {
18        this.width = width;
19        this.height = height;
20    }
21    
22    public int area() {
23        return width * height;
24    }
25}
26
27// Usage
28Rectangle r1 = new Rectangle();       // 1x1
29Rectangle r2 = new Rectangle(5);      // 5x5 square
30Rectangle r3 = new Rectangle(4, 6);   // 4x6
31
32System.out.println(r1.area());  // 1
33System.out.println(r2.area());  // 25
34System.out.println(r3.area());  // 24

Copy constructor and inheritance constructor chaining

java
1// Copy Constructor
2public class Student {
3    private String name;
4    private int[] scores;
5    
6    public Student(String name, int[] scores) {
7        this.name = name;
8        this.scores = scores;
9    }
10    
11    // Copy constructor - creates a copy of another object
12    public Student(Student other) {
13        this.name = other.name;
14        // Deep copy of array!
15        this.scores = Arrays.copyOf(other.scores, other.scores.length);
16    }
17    
18    public void setScore(int index, int value) {
19        scores[index] = value;
20    }
21}
22
23// Usage
24Student original = new Student("Alice", new int[]{90, 85, 88});
25Student copy = new Student(original);  // Copy constructor
26
27original.setScore(0, 100);
28
29// Copy is independent - has its own scores array
30System.out.println(original.scores[0]);  // 100
31System.out.println(copy.scores[0]);      // 90 (unchanged)
32
33// Inheritance: super() constructor call
34public class Animal {
35    protected String name;
36    public Animal(String name) {
37        this.name = name;
38    }
39}
40
41public class Dog extends Animal {
42    private String breed;
43    
44    public Dog(String name, String breed) {
45        super(name);  // MUST be first line - calls parent constructor
46        this.breed = breed;
47    }
48}

Use Cases

  • Object initialization with required values
  • Setting default values
  • Input validation during creation
  • Dependency injection
  • Copy constructor for cloning
  • Builder pattern initialization

Common Mistakes to Avoid

  • Adding return type to constructor
  • Forgetting this() or super() must be first
  • Not providing no-arg when parameterized exists
  • Shallow copy in copy constructor
  • Calling overridable methods in constructor
  • Complex logic in constructors (use factory)