Skip to content

Commit 4ab745b

Browse files
committed
feat: Add DownCasting class demonstrating upcasting and explicit downcasting
Add a program that: - Defines a parent class `AnimalFamily` and a subclass `Cat` - Shows upcasting by referencing a `Cat` object with a parent class type - Demonstrates explicit downcasting to access subclass-specific methods - Calls methods from both superclass and subclass to illustrate inheritance behavior.
1 parent 6080098 commit 4ab745b

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed
Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,18 @@
1-
/*
2-
Downcasting: means the typecasting of a parent object to a child object.cannot be implicit.
3-
4-
https://www.scaler.com/topics/upcasting-and-downcasting-in-java/
5-
6-
Explicit Down-casting:
7-
8-
When a subclass type refers to an object of the parent class, the process is referred to as down-casting.
9-
If it is done manually, the compiler issues a runtime ClassCastException error.
10-
It can only be done by using the instanceof operator.Only the downcast of an object that has already been upcast is possible.
11-
*/
12-
131
import java.io.*;
142
class AnimalFamily {
15-
public void eat()
16-
{
3+
public void eat() {
174
System.out.println("The animal is eating.");
185
}
196
}
207

218
class Cat extends AnimalFamily {
22-
public void meow()
23-
{
9+
public void meow() {
2410
System.out.println("The cat is meowing.");
2511
}
2612
}
2713

2814
class DownCasting {
29-
public static void main(String[] args)
30-
{
15+
public static void main(String[] args) {
3116
AnimalFamily animal = new Cat(); // Upcasting: Cat object is referenced by AnimalFamily
3217
animal = new Cat(); // New Cat object, previous one is lost (Garbage Collected)
3318
animal = new Cat(); // Another new Cat object
@@ -37,4 +22,17 @@ public static void main(String[] args)
3722
Cat cat = (Cat)animal;
3823
cat.meow();
3924
}
40-
}
25+
}
26+
27+
/*
28+
Down-casting: means the typecasting of a parent object to a child object.cannot be implicit.
29+
30+
https://www.scaler.com/topics/upcasting-and-downcasting-in-java/
31+
32+
Explicit Down-casting:
33+
34+
When a subclass type refers to an object of the parent class, the process is referred to as down-casting.
35+
If it is done manually, the compiler issues a runtime ClassCastException error.
36+
It can only be done by using the instanceof operator.
37+
Only the downcast of an object that has already been upcast is possible.
38+
*/

0 commit comments

Comments
 (0)