Commit 874375d
committed
feat: Demonstrate use of super keyword for accessing parent variables and methods
WHAT the code does:
- Defines base class Vehical:
- int maxSpeed = 120.
- Method vroom() prints "Vroom Vroom".
- Defines subclass Car2:
- Declares its own int maxSpeed = 100, hiding the parent field.
- display() uses super.maxSpeed to access the parent’s variable (prints 120).
- Overrides vroom() but calls super.vroom() inside, reusing the parent implementation.
- main():
- Creates Car2 instance.
- Calls display() → prints parent’s maxSpeed (120).
- Calls vroom() → executes Vehical’s vroom() via super, printing "Vroom Vroom".
WHY this matters:
- Shows **field hiding** vs **method overriding**:
- Fields in Java are hidden, not overridden. `super.maxSpeed` allows access to parent’s version.
- Methods can be overridden. Using `super.methodName()` allows calling the parent’s version.
- Demonstrates **super keyword usage**:
- Access parent’s variables when child defines its own with the same name.
- Call parent’s methods from an overridden method in the child.
- Also usable to call parent constructors (`super(...)`), though not shown here.
HOW it works:
1. new Car2() creates an object with both parent and child fields (two copies of maxSpeed).
2. display() prints parent’s field (120).
3. Car2.vroom() executes, which explicitly calls Vehical.vroom() using super → "Vroom Vroom".
Tips and gotchas:
- Use `super` when the child needs to leverage or extend behavior of the parent.
- Fields don’t participate in polymorphism — accessing `maxSpeed` without super in Car2 would give 100, but with super it gives 120.
- Always call super() in constructors if the parent has required initialization.
Use-cases / analogies:
- Child reusing parent’s “tools” (methods or data) while also defining its own versions.
- Like a son saying “I’ll use my father’s way of driving” (`super.vroom()`) but also having his own car speed field.
Short key: java super-keyword method-overriding field-hiding inheritance.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 505d921 commit 874375d
1 file changed
+11
-16
lines changedLines changed: 11 additions & 16 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | | - | |
6 | | - | |
| 4 | + | |
7 | 5 | | |
8 | 6 | | |
9 | 7 | | |
10 | 8 | | |
11 | | - | |
12 | | - | |
| 9 | + | |
13 | 10 | | |
| 11 | + | |
14 | 12 | | |
15 | | - | |
16 | | - | |
| 13 | + | |
| 14 | + | |
17 | 15 | | |
18 | 16 | | |
19 | 17 | | |
20 | 18 | | |
21 | | - | |
22 | | - | |
| 19 | + | |
23 | 20 | | |
24 | 21 | | |
25 | 22 | | |
26 | 23 | | |
27 | | - | |
28 | | - | |
29 | | - | |
30 | | - | |
| 24 | + | |
| 25 | + | |
31 | 26 | | |
32 | 27 | | |
33 | 28 | | |
34 | 29 | | |
35 | 30 | | |
36 | | - | |
| 31 | + | |
37 | 32 | | |
38 | 33 | | |
39 | | - | |
| 34 | + | |
0 commit comments