BCA / B.Tech 17 min read

Constructors in Java

Constructors in Java:

A constructor in Java is a special type of method that is used to initialize an object when it is created. It is called automatically at the time of object creation.

Key Properties of a Constructor:
  • A constructor must have the same name as the class.
  • A constructor does not have an explicit return type, not even `void`.

Types of Constructors:
  1. Default Constructor (No-Arg Constructor): A constructor that has no parameters. If a class does not have any constructor defined, the Java compiler provides a default constructor automatically.
  2. Parameterized Constructor: A constructor that accepts one or more parameters. It is used to initialize the object with specific values at the time of creation.

A class can have multiple constructors, each with a different parameter list. This concept is known as constructor overloading. It provides flexibility for creating objects in different ways.