DEV Community

Mercy
Mercy

Posted on

Constructors in java

Key lessons from this article

  • What is a default no-argument constructor?
  • How is a default no-argument constructor used?
  • How to call constructors?
  • Advantages of using constructors.

Five constructor rules

  • The first statement of a constructor is a call to another constructor using this() or a call to a constructor in the direct parent using super().
  • The super() may not be used after the first statement of the constructor.
  • If no super call is declared in a constructor, Java will insert a no-argument super as the first statement of the constructor.
  • If the parent doesn't define a no-argument constructor and the child doesn't define any constructor, the compiler will throw an error and try to insert a default no-argument constructor.

What is a constructor in Java?

Image description
A constructor in Java is a special method used to initialize objects. It is called automatically when a class object is created and is responsible for setting the initial state and values of the object's attributes.

Every class has at least one constructor. If no constructor is declared the compiler will insert a default no-argument constructor.

Image description

Here is the output

Image description

If a parent constructor takes arguments, the super() constructor would also take arguments.
We refer to super() command as a parent constructor even those that take an argument.
In Java, if a constructor does not explicitly call another constructor in the same class (using this(...)) or a parent constructor (using super(...)), then the Java compiler will implicitly insert a call to the no-argument constructor of the parent class (super()). This behavior ensures that the parent class's initialization logic is run before the child class's logic

Image description

Subclasses can define no-argument constructor even if their parents do not. The constructor of the child maps a parent constructor via an explicit call of the super() command.

How to call constructors

The parent constructors are always executed before the child constructor. They are called when you create a new instance of a class using the new keyword.Each constructor in a class can have different parameters (constructor overloading), allowing for different ways to initialize an object.

1. Calling Constructors with new
When you create an instance of a class using new, the corresponding constructor is called. If there are multiple constructors, the one with matching parameters is chosen.

Image description

  • new Person() calls the no-argument constructor.

  • new Person("Alice", 25) calls the constructor with two parameters.

2. Calling One Constructor from Another (Constructor Chaining)
Within a class, you can call one constructor from another using this(...). This is called constructor chaining. It helps to reuse constructor logic and avoid code duplication.

Image description
In the above, new Car("Toyota") calls the constructor with one parameter, which then calls this(model, 2023) to chain to the constructor with two parameters.

3. Calling the Parent Constructor (super(...))
When a class extends another class, you can call a constructor of the parent class using super(...). This is required if the parent class does not have a no-argument constructor or if you want to pass specific arguments to a parent constructor.
Image description.
In the above,
new Dog("Buddy")calls theDogconstructor, which then callssuper("Mammal")to initialize thetypefield in theAnimal` class.

Advantages of using constructors

1. Object Initialization: Constructors ensure that an object is in a valid state as soon as it’s created. By initializing fields and setting up essential data, constructors guarantee that the object is ready to be used immediately after instantiation.

2. Overloading Flexibility: Java allows constructors to be overloaded, enabling multiple ways to create and initialize an object. This flexibility helps in handling various initialization requirements and simplifies object creation in different contexts.

3. Encapsulation of Initialization Logic: Constructors encapsulate initialization logic, keeping setup code organized and allowing easy modification without impacting the rest of the class or client code. This also hides complex setup details, simplifying object creation for other developers.

4. Immutable Object Creation: For classes designed to be immutable, constructors allow setting all required fields once, making it impossible to modify them later. This is crucial for creating reliable, thread-safe objects in multi-threaded applications.

5. Code Reusability via Chaining: Constructors can call one another (using this(...) or super(...)), enabling shared initialization logic within the same class or from parent classes. This helps to avoid redundancy and promotes cleaner, DRY (Don’t Repeat Yourself) code.

6. Enforcing Required Fields: Constructors allow mandatory fields to be set at the time of object creation. Without constructors, required fields could be missed, potentially leaving the object in an incomplete or inconsistent state.

7. Enhanced Readability: Constructors improve code readability by making it explicit which parameters are essential for object creation. This makes it clear to other developers which values are needed to initialize the object properly.

8. Automatic Call to Superclass Constructor: Constructors automatically call the superclass constructor, ensuring that the parent’s fields and initialization logic are executed first. This automatic calling supports inheritance by setting up the entire class hierarchy.

9. Supports Dependency Injection: Constructors are ideal for dependency injection, especially in frameworks like Spring, where dependencies can be injected via constructor parameters. This approach enhances modularity, testability, and flexibility in applications.

10. Simplifies Object Creation in APIs and Libraries: For library or API users, constructors provide a straightforward way to create objects with minimal setup. This improves the user experience, as they don’t need to perform complex configuration after creating an object.

Conclusion
Constructors play a crucial role in Java, providing a robust mechanism for object initialization and setup. They ensure that objects are created in a valid state, support flexible initialization through overloading, and promote code reusability with chaining and encapsulation of logic. By calling parent constructors when extending classes, Java maintains a structured approach to inheritance, reinforcing object integrity and readability.

Top comments (1)

Collapse
 
devnenyasha profile image
Melody Mbewe

Great job providing valuable insights that will surely help both beginners and experienced developers enhance their skills! Keep up the excellent work!