Skip to main content

How to overcome class cast Exception

How to overcome class cast Exception
  •  How to avoid class cast exception
  •  The class cast exception can be avoided by using instanceof operator
  •  This Operator will help us to know whether object having the require class property.
Use of instance of operator
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package casting;
 
class Demo6
{
 
	int k=10;
 
	void test()
	{
		System.out.println("running test method");
	}
}
 
class Sample6 extends Demo6
{
 
	double d=12.3;
	void disp()
	{
		System.out.println("running disp method");
	}
}
 
class Run6 extends Sample6
{
 
	boolean b=true;
	void run()
	{
		System.out.println("running run method");
	}
 
}
 
class start6
{
 
	void execution(Demo6 arg1)
	{
 
		System.out.println("running execution method");
 
		//using arg1 we can access Demo12 and its super class property
 
		System.out.println("k value: "+arg1.k);
		arg1.test();
 
		if(arg1 instanceof Sample6)
		{
 
			Sample6 rf1=(Sample6) arg1;//downcasting
 
			System.out.println("d value: "+rf1.d);
 
			rf1.disp();
 
		}
		else
		{
 
		System.out.println("object does not property of sample6 class");
 
		}
 
 
	}	
}
 
public class OvercomeClasscastException 
{
 
	public static void main(String[] args) {
 
		System.out.println("**************************");
 
		start6 st=new start6();
 
		st.execution(new Demo6());
 
		System.out.println("**************************");
 
	}
 
}
 
output:
 
**************************
running execution method
k value: 10
running test method
object does not property of sample6 class
**************************