Commit 9f45134
committed
feat: Add multilevel inheritance demo with average calculation
WHAT the code does:
Defines a four-level inheritance chain:
- DemoA: defines int x = 5.
- DemoB extends DemoA: adds int y = 7.
- DemoC extends DemoB: introduces double average and calcAverage() method, which computes (x + y) / 2.0.
- DemoD extends DemoC: currently empty but available for extension.
Defines DemoE with main():
- Instantiates DemoD.
- Calls calcAverage() to print average of x and y.
WHY this matters:
Demonstrates multilevel inheritance in Java, showing how subclasses inherit fields and methods from all parent classes.
Illustrates method logic depending on fields defined across multiple parent classes.
Provides an educational example of how data flows through an inheritance hierarchy.
HOW it works:
objD inherits x from DemoA and y from DemoB.
calcAverage() in DemoC uses both fields, computing (5 + 7) / 2.0 = 6.0.
Output: 6.0.
Tips and gotchas:
Multilevel inheritance is supported in Java, but deep hierarchies can lead to fragile designs; composition is often preferred in real-world applications.
Fields x and y are package-private (default access); encapsulation via private + getters/setters would improve design.
DemoD is empty, but can be used to add further behavior while still retaining access to x, y, and calcAverage().
Method naming: calcAverage() could return the value instead of printing for better reuse.
Use-cases:
Educational demonstration of multilevel inheritance.
Introductory example of reusing fields from ancestor classes in calculations.
Foundation for understanding constructor chaining and method overriding in deeper hierarchies.
Short key: class-demoa-demod multilevel-inheritance average-calculation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d887f79 commit 9f45134
1 file changed
+13
-15
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | | - | |
6 | | - | |
| 4 | + | |
| 5 | + | |
7 | 6 | | |
8 | 7 | | |
9 | | - | |
10 | | - | |
| 8 | + | |
| 9 | + | |
11 | 10 | | |
12 | | - | |
13 | | - | |
| 11 | + | |
| 12 | + | |
14 | 13 | | |
15 | 14 | | |
16 | 15 | | |
17 | 16 | | |
18 | | - | |
19 | | - | |
20 | | - | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
21 | 20 | | |
22 | | - | |
23 | | - | |
24 | | - | |
25 | | - | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
26 | 24 | | |
27 | 25 | | |
28 | 26 | | |
| |||
0 commit comments