Commit 1036eaf
committed
π docs: Explain difference between constructors and methods in Java
π Short Key: constructor-vs-method
π§ Logic & Highlights:
- **Constructor**: special block to initialize objects, name matches class, no return type, invoked automatically with `new`
- **Method**: defines object behavior, can have any name, must have a return type, invoked explicitly
π Key Differences:
- Purpose: initialize object vs. perform actions
- Name: same as class vs. any name
- Return type: none vs. required
- Invocation: automatic vs. explicit
- Inheritance: not inherited vs. inherited/overridable
- Overloading: supported for both
π Added Comparison Table:
| Feature | Constructor | Method |
|---------------|------------------------------------|---------------------------------------|
| Purpose | Initialize object | Define behavior/operations |
| Name | Same as class | Any valid identifier |
| Return Type | None | Must return type (`int`, `void`, etc.)|
| Invocation | Auto on object creation | Explicit call on object |
| Inheritance | Not inherited | Inherited and overridable |
| Overloading | Supported | Supported |
π Example:
- Created a `Car` class with parameterized constructor to set `model` & `year`
- Added `displayDetails()` method to show details
- Demonstrated usage in `Main` class
π― Learning Outcomes:
- Clear understanding of when and how to use constructors vs methods**
- Demonstrated real-world example with `Car` class.
Signed-off-by: Somesh diwan <[email protected]>1 parent 1770d66 commit 1036eaf
File tree
1 file changed
+2
-1
lines changed- Section10Methods/Methods 2.O/src
1 file changed
+2
-1
lines changedLines changed: 2 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
11 | | - | |
| 11 | + | |
| 12 | + | |
12 | 13 | | |
13 | 14 | | |
14 | 15 | | |
| |||
0 commit comments