Skip to content

Commit 8dc5fe1

Browse files
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

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed
Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,21 @@
1-
//Need Practice the same thing again.
2-
//Solve Again Revise This.
3-
4-
class Rectangle
5-
{
1+
class Rectangle {
62
int length;
73
int breadth;
84

9-
Rectangle(int length, int breadth)
10-
{
5+
Rectangle(int length, int breadth) {
116
this.length = length; // Fixed the typo
127
this.breadth = breadth;
138
}
149

15-
void display()
16-
{
10+
void display() {
1711
System.out.println("Length is: " + length);
1812
System.out.println("Breadth is: " + breadth);
1913
}
2014
}
2115

22-
public class thisVsSuper
23-
{
24-
public static void main(String[] args)
25-
{
16+
public class thisVsSuper {
17+
public static void main(String[] args) {
2618
Rectangle rect = new Rectangle(10, 3);
2719
rect.display(); // Call display() to print values
2820
}
29-
}
21+
}

0 commit comments

Comments
 (0)