Java

Constructors and Object Initialization

In the previous articles, we explored Java objects, object lifecycle, and classes. Now it’s time to dive into one of the most important topics for the Oracle Certified Professional (OCP) Java 21 exam: constructors and object initialization.

Understanding how objects are initialized is essential because many certification questions test initialization order, constructor chaining, and the use of this and super.


What is a Constructor?

A constructor is a special method used to initialize an object when it is created.

Constructors are automatically invoked when an object is instantiated using the new keyword.

Example:

public class Employee {

    public Employee() {
        System.out.println("Employee created");
    }

    public static void main(String[] args) {
        Employee employee = new Employee();
    }
}

Output:

Employee created

Constructor Rules

A constructor:

  • Has the same name as the class
  • Does not have a return type
  • Can accept parameters
  • Can be overloaded

The following is NOT a constructor:

public void Employee() {
}

This is simply a method named Employee because it has a return type (void).


Default Constructor

If a class does not define any constructors, Java automatically provides a default constructor.

Example:

public class Student {
}

Java automatically creates:

public Student() {
    super();
}

This allows the following code to compile:

Student student = new Student();

Important OCP Exam Tip

Once you define any constructor, Java no longer generates a default constructor.

Example:

public class Student {

    public Student(String name) {
    }
}

This will fail:

Student student = new Student();

Compilation error:

constructor Student in class Student cannot be applied to given types

Parameterized Constructors

Constructors often receive information needed to initialize an object.

Example:

public class Employee {

    private String name;

    public Employee(String name) {
        this.name = name;
    }

    public void printName() {
        System.out.println(name);
    }

    public static void main(String[] args) {
        Employee employee = new Employee("John");
        employee.printName();
    }
}

Output:

John

Using the this Keyword

The this keyword refers to the current object.

It is commonly used when constructor parameters have the same name as instance variables.

Example:

public class Employee {

    private String name;

    public Employee(String name) {
        this.name = name;
    }
}

Without this, Java would not know whether name refers to the parameter or the instance variable.


Constructor Overloading

A class may contain multiple constructors with different parameter lists.

Example:

public class Car {

    private String model;
    private int year;

    public Car() {
        this("Unknown", 2025);
    }

    public Car(String model) {
        this(model, 2025);
    }

    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }
}

This allows flexibility when creating objects.

Car car1 = new Car();
Car car2 = new Car("BMW");
Car car3 = new Car("BMW", 2025);

Constructor Chaining

Constructor chaining occurs when one constructor calls another constructor in the same class.

This is done using this().

Example:

public class User {

    private String username;
    private String role;

    public User() {
        this("guest");
    }

    public User(String username) {
        this(username, "USER");
    }

    public User(String username, String role) {
        this.username = username;
        this.role = role;
    }
}

Benefits include:

  • Reduced code duplication
  • Easier maintenance
  • Centralized initialization logic

Calling Parent Constructors with super()

When a subclass is instantiated, Java first executes the parent constructor.

Example:

class Animal {

    public Animal() {
        System.out.println("Animal constructor");
    }
}

class Dog extends Animal {

    public Dog() {
        System.out.println("Dog constructor");
    }
}

Running:

new Dog();

Produces:

Animal constructor
Dog constructor

Java automatically inserts:

super();

as the first statement in a constructor if one is not explicitly provided.


Rules for this() and super()

The OCP exam frequently tests these rules.

Rule 1

this() must be the first statement in a constructor.

Valid:

public Employee() {
    this("Unknown");
}

Invalid:

public Employee() {
    System.out.println("Creating employee");
    this("Unknown");
}

Rule 2

super() must also be the first statement.

Valid:

public Employee() {
    super();
}

Invalid:

public Employee() {
    System.out.println("Hello");
    super();
}

Rule 3

A constructor may call either this() or super(), but never both.

Invalid:

public Employee() {
    this("John");
    super();
}

Instance Initialization Blocks

Java allows initialization code outside of constructors.

Example:

public class Employee {

    {
        System.out.println("Instance block");
    }

    public Employee() {
        System.out.println("Constructor");
    }

    public static void main(String[] args) {
        new Employee();
    }
}

Output:

Instance block
Constructor

Instance initialization blocks execute before the constructor.


Static Initialization Blocks

Static blocks execute once when the class is loaded.

Example:

public class Employee {

    static {
        System.out.println("Static block");
    }

    public static void main(String[] args) {
        new Employee();
        new Employee();
    }
}

Output:

Static block

The static block runs only once regardless of how many objects are created.


Java Object Initialization Order

This is one of the most tested OCP topics.

Consider:

public class Employee {

    static {
        System.out.println("Static Block");
    }

    {
        System.out.println("Instance Block");
    }

    public Employee() {
        System.out.println("Constructor");
    }

    public static void main(String[] args) {
        new Employee();
    }
}

Output:

Static Block
Instance Block
Constructor

The order is:

  1. Static variables
  2. Static initialization blocks
  3. Instance variables
  4. Instance initialization blocks
  5. Constructor

Remember this sequence for the exam.


Common OCP Exam Traps

Trap 1: Constructor with Return Type

public void Employee() {
}

This is not a constructor.


Trap 2: Missing Default Constructor

public class Employee {

    public Employee(String name) {
    }
}

This fails:

new Employee();

Trap 3: Recursive Constructor Calls

public Employee() {
    this();
}

Compilation error.


Trap 4: Incorrect Initialization Order

Always remember:

Static → Instance → Constructor

Practice Questions

Question 1

What is the output?

public class Test {

    {
        System.out.println("Instance");
    }

    public Test() {
        System.out.println("Constructor");
    }

    public static void main(String[] args) {
        new Test();
    }
}

A. Constructor Instance

B. Instance Constructor

C. Compilation Error

D. No Output

Answer: B


Question 2

Will this compile?

public class Test {

    public void Test() {
    }
}

Answer:

Yes.

It compiles because Test() is a method, not a constructor.


Question 3

What is the output?

class Parent {

    Parent() {
        System.out.println("Parent");
    }
}

class Child extends Parent {

    Child() {
        System.out.println("Child");
    }

    public static void main(String[] args) {
        new Child();
    }
}

Answer:

Parent
Child

Summary

Constructors are responsible for initializing objects and are a fundamental topic in both real-world Java development and the OCP Java 21 certification exam.

Key takeaways:

  • Constructors have no return type
  • Constructor names must match the class name
  • Java generates a default constructor only when none are defined
  • Use this() for constructor chaining
  • Use super() to call parent constructors
  • Instance blocks execute before constructors
  • Static blocks execute once when the class loads
  • Initialization order is heavily tested on the OCP exam

Mastering constructors and object initialization will provide a solid foundation for the next topic in this series: Inheritance and Polymorphism.

Leave a Reply

Your email address will not be published. Required fields are marked *