forked from MLSA-Mehran-UET/Learn-to-code-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDowncasting.java
34 lines (23 loc) · 853 Bytes
/
Downcasting.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Downcasting is when a child class type reference variable point to/references
// to a parent object or parentclass type
package downcasting;
class Animal
{
}
public class Downcasting extends Animal{
static void method(Animal a) {
if(a instanceof Downcasting){
Downcasting d=(Downcasting)a;//downcasting
System.out.println("ok downcasting performed");
}
}
public static void main(String[] args) {
//downcasting is not possible in this way will give compile-time error
// Downcasting d=new Animal();
//Compiles successfully but ClassCastException is thrown at runtime if we use type casting as shown under :
// Dog d=(Dog)new Animal();
//but we can do it as under
Animal a=new Downcasting();
Downcasting.method(a);
}
}