Commit c8c8a8e
committed
feat: Add ConstructorDemo1 with overloaded constructors for rectangles and squares
WHAT the code does:
Defines ConstructorDemo1 with private fields length and breadth.
Implements three constructors:
- Default constructor: sets length and breadth to 1.
- Parameterized constructor (double l, double b): initializes with given length and breadth.
- Square constructor (double s): sets both length and breadth to the same value.
Provides display() method to print length and breadth.
Defines Constructor with main():
- Demonstrates creation of objects using all three constructors.
- Calls display() to show initialized values.
WHY this matters:
Demonstrates constructor overloading in Java for flexible object initialization.
Encapsulates rectangle and square representation in a single class.
Illustrates default, parameterized, and convenience constructors.
Shows how constructors eliminate the need for repetitive setter calls after object creation.
HOW it works:
c1 = new ConstructorDemo1(); → length = 1, breadth = 1.
c2 = new ConstructorDemo1(5.0, 10.0); → length = 5, breadth = 10.
c3 = new ConstructorDemo1(7.0); → length = breadth = 7.
Each object calls display(), printing initialized values.
Tips and gotchas:
Field values are private, enforcing encapsulation; display() provides controlled access.
Constructors with similar signatures can create ambiguity; here, double vs (double,double) resolves clearly.
Adding validation inside constructors (e.g., rejecting negative dimensions) improves robustness.
Overriding toString() could replace display() for more idiomatic printing.
Use-cases:
Educational demonstration of constructor overloading in Java.
Practical design for representing rectangles and squares in geometry problems.
Foundation for extending into area, perimeter, or volume calculations.
Short key: class-constructordemo1 constructor-overloading rectangle-square.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e474d62 commit c8c8a8e
1 file changed
+13
-19
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
6 | | - | |
7 | | - | |
| 5 | + | |
8 | 6 | | |
9 | 7 | | |
10 | 8 | | |
11 | | - | |
12 | | - | |
| 9 | + | |
13 | 10 | | |
14 | 11 | | |
15 | 12 | | |
16 | | - | |
17 | | - | |
| 13 | + | |
18 | 14 | | |
19 | 15 | | |
| 16 | + | |
20 | 17 | | |
21 | | - | |
22 | | - | |
| 18 | + | |
23 | 19 | | |
24 | 20 | | |
25 | 21 | | |
26 | 22 | | |
27 | | - | |
28 | | - | |
29 | | - | |
30 | | - | |
| 23 | + | |
| 24 | + | |
31 | 25 | | |
32 | 26 | | |
33 | 27 | | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
34 | 31 | | |
35 | | - | |
36 | | - | |
37 | | - | |
| 32 | + | |
38 | 33 | | |
39 | | - | |
40 | 34 | | |
41 | 35 | | |
42 | 36 | | |
43 | 37 | | |
44 | | - | |
| 38 | + | |
0 commit comments