Commit 8dc5fe1
committed
feat: Add Rectangle class with constructor using this keyword for field initialization
WHAT the code does:
Defines Rectangle with fields:
- length and breadth.
Constructor:
- Rectangle(int length, int breadth) uses this.length = length and this.breadth = breadth to assign parameters to instance variables.
Method:
- display(): prints the rectangle’s dimensions.
Defines thisVsSuper with main():
- Creates Rectangle object (10, 3).
- Calls display() to print field values.
WHY this matters:
Demonstrates the use of **this** to resolve naming conflicts between constructor parameters and instance variables.
Reinforces that without this, assignments like length = length would only reassign the local parameter, leaving the field uninitialized.
Shows a practical example of encapsulating initialization logic in constructors.
HOW it works:
Rectangle rect = new Rectangle(10,3):
- this.length = 10, this.breadth = 3.
display() prints:
Length is: 10
Breadth is: 3.
Tips and gotchas:
Using this improves readability and prevents subtle bugs in constructors and setters.
If parameter names were different from field names, this would not be strictly required, though often still used for clarity.
Class name thisVsSuper suggests a comparison, but current code only demonstrates this keyword, not super.
Encapsulation could be improved by making fields private and adding getters/setters.
Use-cases:
Educational example for explaining the role of this in constructors.
Helps beginners understand scope resolution in Java.
Foundation for extending into examples comparing this vs super for constructors and method calls.
Short key: class-rectangle constructor-this field-initialization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 0c085ca commit 8dc5fe1
1 file changed
+6
-14
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
| 1 | + | |
6 | 2 | | |
7 | 3 | | |
8 | 4 | | |
9 | | - | |
10 | | - | |
| 5 | + | |
11 | 6 | | |
12 | 7 | | |
13 | 8 | | |
14 | 9 | | |
15 | | - | |
16 | | - | |
| 10 | + | |
17 | 11 | | |
18 | 12 | | |
19 | 13 | | |
20 | 14 | | |
21 | 15 | | |
22 | | - | |
23 | | - | |
24 | | - | |
25 | | - | |
| 16 | + | |
| 17 | + | |
26 | 18 | | |
27 | 19 | | |
28 | 20 | | |
29 | | - | |
| 21 | + | |
0 commit comments