Commit 8aeaf36
committed
feat: Demonstrate constructor chaining with super() and overloaded constructors
WHAT the code does:
- Defines class A with two constructors:
- Default constructor → prints "in A".
- Parameterized constructor (int n) → calls super() (Object’s constructor implicitly) and prints "in A int".
- Defines class B extending A:
- Default constructor → implicitly calls A’s default constructor, then prints "in B".
- Parameterized constructor (int m) → explicitly calls super(m) to invoke A’s parameterized constructor, then prints "in B in int".
- In main():
- A obj2 = new A(9); → runs A’s parameterized constructor, prints "in A int".
- B obj1 = new B(5); → calls A(int) via super(m), prints "in A int", then prints "in B in int".
WHY this matters:
- Demonstrates **constructor chaining**:
- Every constructor in a subclass must call a constructor of the parent class (either implicitly or explicitly).
- `super()` → calls parent constructor.
- `this()` → can call another constructor in the same class.
- Highlights difference between:
- Default constructor chaining → A() then B().
- Parameterized constructor chaining → A(int) then B(int).
- Shows the order: parent constructor always runs before child constructor.
HOW it works:
1. new A(9) → calls A(int) → prints "in A int".
2. new B(5) → calls B(int).
- B(int) explicitly calls super(m) → invokes A(int) → prints "in A int".
- Then B(int) continues → prints "in B in int".
Tips and gotchas:
- If a parent class doesn’t have a no-argument constructor, subclass constructors must explicitly call one of the parent’s parameterized constructors.
- Java inserts `super();` implicitly in constructors if no explicit call is present.
- Constructor chaining is critical for proper initialization of inheritance hierarchies.
Use-cases / analogies:
- Parent handing down setup instructions before child’s setup can proceed.
- Like building a house: foundation (parent) must be laid before adding walls and windows (child).
Short key: java constructor-chaining super this inheritance initialization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent fa8e4be commit 8aeaf36
1 file changed
+7
-12
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
| 2 | + | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
7 | | - | |
8 | | - | |
| 6 | + | |
9 | 7 | | |
10 | 8 | | |
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | | - | |
15 | | - | |
16 | | - | |
| 12 | + | |
| 13 | + | |
17 | 14 | | |
18 | 15 | | |
19 | 16 | | |
20 | | - | |
21 | | - | |
| 17 | + | |
22 | 18 | | |
23 | 19 | | |
24 | 20 | | |
25 | 21 | | |
26 | 22 | | |
27 | | - | |
28 | | - | |
| 23 | + | |
29 | 24 | | |
30 | 25 | | |
31 | 26 | | |
| |||
0 commit comments