Java Constructor
In Java, a constructor is a special type of method that is used to initialize objects. It is automatically called when an object of a class is created. Constructors help in setting initial values for object attributes.
Characteristics of a Constructor#
- A constructor has the same name as the class.
- It does not have a return type, not even
void
. - It is automatically invoked when an object is created.
- Constructors can have parameters to initialize objects with different values.
Types of Constructors in Java#
1. Default Constructor#
A default constructor is a constructor without parameters. If no constructor is defined in a class, Java automatically provides a default constructor.
Example:#
Output:#
2. Parameterized Constructor#
A parameterized constructor allows us to pass values while creating an object.
Example:#
Output:#
3. Copy Constructor#
A copy constructor creates a new object by copying the values of an existing object.
Example:#
Output:#
Constructor Overloading#
Constructor overloading allows a class to have multiple constructors with different parameters.
Example:#
Output:#
Conclusion#
Constructors are essential in Java for initializing objects efficiently. We learned about:
- Default constructors (automatically created if no constructor is defined).
- Parameterized constructors (used to assign values while creating objects).
- Copy constructors (used to create a new object by copying values from another object).
- Constructor overloading (multiple constructors with different parameters).