Java Constructors
🔹 Java Constructors
A constructor in Java is a special method used to initialize objects. It is called automatically when an object is created.
✅ 1. Key Features of Constructors
-
Same name as the class
-
No return type (not even
void) -
Can have parameters
-
Used to initialize instance variables
-
Can be overloaded
✅ 2. Types of Constructors
-
Default Constructor – No parameters; provided automatically if no constructor is defined.
-
Parameterized Constructor – Takes parameters to initialize an object with specific values.
-
No-Arg Constructor – A user-defined constructor without parameters (similar to default).
✅ 3. Example 1: Default Constructor
📌 Output:
✅ 4. Example 2: Parameterized Constructor
📌 Output:
✅ 5. Example 3: Constructor Overloading
📌 Output:
✅ 6. Key Points About Constructors
-
Constructor name must match the class name.
-
No return type, not even void.
-
Can be overloaded to provide multiple ways of initializing objects.
-
Automatically called when an object is created.
-
thiskeyword can be used to refer to current object or call another constructor.
