Skip to content

Commit c388241

Browse files
committed
feat: Implement example demonstrating upcasting and downcasting in Java with method overriding
This commit adds a Java program that illustrates key object-oriented programming concepts: - Upcasting (child to parent reference) - Downcasting (parent reference back to child) - Method overriding and dynamic method dispatch Key changes: - Defined a `Parent` class with a `name` attribute and a `method()` printing a message - Defined a `Child` class that extends `Parent`, adds an `id` attribute, and overrides the `method()` - In the `main()` method: - Performed **upcasting**: `Parent p = new Child();` and demonstrated access to inherited fields and overridden methods - Showed **method dispatch behavior**: `p.method()` executes the overridden method in `Child` - Performed **explicit downcasting** safely: `(Child)p` to access subclass-specific field `id` - Printed both inherited and child-specific data to verify proper object behavior after downcasting This example reinforces Java's runtime polymorphism and the correct approach to accessing subclass features after safe downcasting. Signed-off-by: Somesh diwan <[email protected]>
1 parent f75702d commit c388241

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed
Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,37 @@
11
class Parent {
22
String name;
3-
void method()
4-
{
3+
4+
void method() {
55
System.out.println("Method from Parent");
66
}
77
}
8+
89
class Child extends Parent {
910
int id;
10-
@Override void method()
11-
{
11+
12+
@Override
13+
void method() {
1214
System.out.println("Method from Child");
1315
}
1416
}
17+
1518
public class UpDownCasting {
16-
public static void main(String[] args)
17-
{
19+
public static void main(String[] args) {
20+
1821
/*Upcasting*/
1922
Parent p = new Child();
2023
p.name = "Up Casting";
2124
System.out.println(p.name);
25+
2226
/*parent class method is overridden method hence this will be executed*/
2327
p.method();
2428

2529
/* Trying to Downcasting Implicitly Child c = new Parent(); - > compile time error Downcasting Explicitly*/
2630
Child c = (Child)p;
2731
c.id = 1;
32+
2833
System.out.println(c.name);
2934
System.out.println(c.id);
3035
c.method();
3136
}
32-
}
37+
}

0 commit comments

Comments
 (0)