Commit 2d76078
committed
feat: Add ExampleOverriding to demonstrate method overriding and upcasting
WHAT the code does:
Defines class car with methods:
- start(): prints "Car Started".
- accelerate(): prints "Car is Accelerated".
- changegear(): prints "Manually We Can Change Car Gear".
Defines subclass LuxaryCar extending car:
- Overrides start() to print "Baap Hu Tera".
- Overrides changegear() to print "Automatic Start and Change Gear".
- Adds openRoof(), specific to LuxaryCar.
Defines ExampleOverriding with main():
- Creates a LuxaryCar object stored in a car reference (upcasting).
- Calls start(), accelerate(), and changegear() to demonstrate polymorphism.
WHY this matters:
Demonstrates **method overriding**, where subclass methods replace superclass behavior at runtime.
Shows **upcasting**: a superclass reference can hold a subclass object.
Illustrates polymorphism: overridden methods are resolved by the actual object type (LuxaryCar), not the reference type (car).
Reinforces that subclass-specific methods (like openRoof()) cannot be called on a superclass reference.
HOW it works:
car c = new LuxaryCar();
- c.start() → resolved at runtime → LuxaryCar.start() → prints "Baap Hu Tera".
- c.accelerate() → not overridden → car.accelerate().
- c.changegear() → overridden → LuxaryCar.changegear().
- c.openRoof() → invalid because car reference type does not declare it.
Tips and gotchas:
Class names should follow Java conventions: Car and LuxuryCar instead of car and LuxaryCar.
Upcasting improves flexibility but restricts access to subclass-only features unless downcasting is used.
System.out.println("Baap Hu Tera") is unconventional—consider clearer domain-appropriate messages for professional code.
openRoof() could be accessed if the reference is explicitly cast back to LuxaryCar.
Use-cases:
Educational demonstration of overriding and polymorphism.
Basis for designing extensible systems where subclasses define specific behavior.
Foundation for patterns like dependency injection and runtime behavior customization.
Short key: class-car luxurycar overriding upcasting polymorphism.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent ce9533f commit 2d76078
1 file changed
+12
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | | - | |
9 | | - | |
| 6 | + | |
| 7 | + | |
10 | 8 | | |
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | 12 | | |
15 | | - | |
16 | | - | |
17 | | - | |
18 | | - | |
| 13 | + | |
| 14 | + | |
19 | 15 | | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
20 | 21 | | |
21 | 22 | | |
22 | 23 | | |
| |||
29 | 30 | | |
30 | 31 | | |
31 | 32 | | |
32 | | - | |
| 33 | + | |
33 | 34 | | |
34 | | - | |
| 35 | + | |
0 commit comments