Constructors

Constructors are essential for object creation and initialization. They are special methods within a class that are invoked automatically when an object of that class is created. Constructors play a key role in ensuring that the object is initialized with the correct values and state when it’s created.

A constructor in Java is a block of code that initializes an object when it is created. Every time an object is instantiated, the constructor is called, and it prepares the object for use by assigning values to its fields or performing any setup actions needed.

In simpler terms, constructors allow you to ensure that your objects start their life in a valid and usable state.

Characteristics of Constructors

  • Same Name as Class: The constructor must have the same name as the class it is a part of. This is a distinctive feature that sets constructors apart from other methods in a class.
  • No Return Type: Unlike methods, constructors do not have a return type (not even void). They are solely used to initialize the object.
  • Automatically Called: A constructor is automatically called when a new instance of a class is created using the new keyword.
  • Can Be Overloaded: Java allows constructor overloading, meaning you can have multiple constructors in a class, each with different parameters.

Use Cases of Constructors

  • Object Initialization: Helps in setting up the initial values of an object.
  • Encapsulation: Hides the complexity of initialization and provides controlled access to properties.
  • Code Reusability: Using constructor overloading, multiple initialization techniques can be provided.
  • Avoiding Null References: Ensures objects are properly initialized before use.
  • Dependency Injection: Helps inject dependencies when creating an object in frameworks like Spring.

Syntax

A constructor in Java follows this basic syntax:

Example