Skip to main content

Class cast Exception

What is class cast Exception
  •  It is exception thrown by jvm during class casting.
  • It is type of run time exception.
When class cast exception occur
  • Whenever we try to perform class casting from one class to another
    class type,if object does not have property the class to which have
    to cast,at that time this exception occur.
Why it is not detected at compile time.
  • During compilation the compiler only check only check relationship between
    classes and object but it is not check the property of object.
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
Example of Class cast Exception
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
package casting;
 
class Demo2
{
	void test()
	{
		 System.out.println("******************");
	}
 
}
 
class Sample2 extends Demo2
    {
 
	  void test1()
	  {
		System.out.println("********************");
	  }	
    }
public class Classtype {
 
	public static void main(String[] args) {
 
		Demo2 rf1=new Sample2();//implicit
		Sample2 rf2=(Sample2)new Demo2();//explicit
	       //Exception because Demo2 does not have property of sample2
	}
}
 
output:
 
Exception in thread "main" java.lang.ClassCastException: 
casting.Demo2 cannot be cast to casting.Sample2
 at casting.Classtype.main(Classtype.java:62)