0
0
Javaprogramming~5 mins

Constructor execution flow in Java

Choose your learning style9 modes available
Introduction

Constructors help create objects by setting up their starting values. Understanding how constructors run helps you know what happens first when you make an object.

When you want to create a new object with specific starting values.
When you have a class with parent and child classes and want to know the order constructors run.
When debugging why some parts of an object are not set as expected after creation.
Syntax
Java
class ClassName {
    ClassName() {
        // constructor code here
    }
}

A constructor has the same name as the class.

It runs automatically when you create an object with new.

Examples
Simple constructor printing a message when an Animal object is created.
Java
class Animal {
    Animal() {
        System.out.println("Animal constructor runs");
    }
}
Child class constructor calls parent constructor first, then runs its own code.
Java
class Dog extends Animal {
    Dog() {
        super(); // calls Animal constructor
        System.out.println("Dog constructor runs");
    }
}
If super() is not written, Java calls the parent constructor automatically first.
Java
class Cat extends Animal {
    Cat() {
        System.out.println("Cat constructor runs");
    }
}
Sample Program

This program shows the order constructors run when creating a Dog object. The Animal constructor runs first, then the Dog constructor.

Java
class Animal {
    Animal() {
        System.out.println("Animal constructor starts");
    }
}

class Dog extends Animal {
    Dog() {
        System.out.println("Dog constructor starts");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
    }
}
OutputSuccess
Important Notes

Java always runs the parent class constructor before the child class constructor.

If you don't write super(), Java adds it automatically as the first line in the child constructor.

Constructors help set up objects step-by-step from parent to child.

Summary

Constructors run automatically when creating objects.

Parent class constructor runs before child class constructor.

Understanding this flow helps you control object setup clearly.