Constructors in Java
π§ What is a Constructor?
A constructor in Java is a special method that is automatically called when an object is created. Its main purpose is to initialize objects.
A constructor has the same name as the class and doesnβt have a return type, not even void
.
β Syntax:
πΈ Types of Constructors:
-
Default Constructor β No parameters.
-
Parameterized Constructor β Takes arguments.
-
Copy Constructor (not built-in like C++, but can be created manually).
π§ͺ Example of Default Constructor:
π§ͺ Parameterized Constructor Example:
π Constructor Overloading:
Java allows multiple constructors with different parameters:
π Key Points:
-
A constructor is invoked automatically when the object is created.
-
No return type.
-
Can be overloaded.
-
Used for initializing objects easily.