Constructor vs Method in Java
ποΈ Constructor
A constructor is a special block used to initialize objects when they are created.
β Key Points:
- Has the same name as the class
-
No return type (not even
void
) - Called automatically when an object is created
- Can be overloaded (multiple constructors with different parameters)
π§ Method
A method is a block of code that performs a specific task.
β Key Points:
- Can have any name
- Must have a return type (or
void
) - Called explicitly using the object
- Used for behavior (e.g., actions, calculations)
π Summary Table:
Feature | Constructor | Method |
---|---|---|
Purpose | Initializes objects | Defines object behavior |
Name | Same as class | Any name |
Return type | No return type | Must have return type (or void) |
Called by | Automatically on object creation | Manually using object |
Inheritance | Not inherited | Inherited by child class |