Skip to content

Commit 9f45134

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

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

Section12Inheritance/src/Demo.java

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
1-
class DemoA
2-
{
1+
class DemoA {
32
int x = 5;
43
}
5-
class DemoB extends DemoA
6-
{
4+
5+
class DemoB extends DemoA {
76
int y = 7;
87
}
9-
class DemoC extends DemoB
10-
{
8+
9+
class DemoC extends DemoB {
1110
double average = 0.0;
12-
void calcAverage()
13-
{
11+
12+
void calcAverage() {
1413
average = (x + y) / 2.0;
1514
System.out.println(average);
1615
}
1716
}
18-
class DemoD extends DemoC
19-
{
20-
// Additional functionality can be added in DemoD if needed
17+
18+
class DemoD extends DemoC {
19+
// Additional functionality can be added in DemoD if needed.
2120
}
22-
class DemoE
23-
{
24-
public static void main(String[] args)
25-
{
21+
22+
class DemoE {
23+
public static void main(String[] args) {
2624
DemoD objD = new DemoD();
2725
objD.calcAverage();
2826
}

0 commit comments

Comments
 (0)