Skip to content

Commit f75702d

Browse files
committed
feat: Demonstrate upcasting and downcasting with method overriding in Java
This commit introduces a Java program that clearly explains the concepts of: - Upcasting (automatic) - Downcasting (manual and type-checked) - Method overriding - `instanceof` check for safe casting Key elements: - Defined a base class `Animal` with a field `name` and a method `makenoise()` - Created a subclass `Dog` that overrides `makenoise()` and adds a new method `growl()` - In the `main` method: - Upcasting: `Animal myAnimal = new Dog();` – a `Dog` object is referenced as its superclass type - Demonstrated dynamic method dispatch: `myAnimal.makenoise()` calls the overridden method in `Dog` - Explained unsafe downcasting: casting `new Animal()` to `Dog` results in `ClassCastException` - Used `instanceof` to safely downcast only when the object is actually an instance of `Dog` - Invoked the `growl()` method after safe downcasting This example emphasizes best practices when working with polymorphism and casting in Java, ensuring both flexibility (via upcasting) and safety (via `instanceof`) during object manipulation. Signed-off-by: Somesh diwan <[email protected]>
1 parent 4f9871e commit f75702d

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

Section5OperatorExpression/src/UpcastingandDowncasting.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public void growl() {
1919

2020
public class UpcastingandDowncasting {
2121
public static void main(String[] args) {
22+
2223
Animal myAnimal = new Dog();
2324
myAnimal.makenoise();
2425
/*Automatically upcasting Dog to Animal.*/
@@ -27,9 +28,9 @@ public static void main(String[] args) {
2728
Dog d = new Dog();
2829
d.makenoise();
2930
d.growl();
30-
*/
31-
31+
*/
3232
/*Unsafe Down-casting (Incorrect)*/
33+
3334
/*
3435
Dog dd = (Dog) new Animal();
3536
dd.growl();
@@ -42,4 +43,4 @@ public static void main(String[] args) {
4243
System.out.println("Downcasting is not possible.");
4344
}
4445
}
45-
}
46+
}

0 commit comments

Comments
 (0)