CCE - ClassCastException In Java | OOps Concept - Math Traders

Latest

CCE - ClassCastException In Java | OOps Concept

 CCE - ClassCastException

It is a class present in java.lang package. This is used as exception class .It is a runtime exception or unchecked exception. 


Q. When it occurs?

Ans - without performing upcast if we try to perform downcast, we will get this type of exception. Or the object which is going to cast another class but doesn't have the property of that particular class then also we get this type of exception.

Q. How to avoid it?

Ans - by using "instanceof" operator. 

Example Of CCE - ClassCastException to avoid runtime exception. 


class Student{// Example of up and down cast 

String name;

int id;

void java(){

System.out.println(name+ " attending java class");

}

}


class DevStudent extends Student{

void advanceJava(){

System.out.println(name+" attending advanceJava class");

}

}


class TestStudent extends Student{

void manual(){

System.out.println(name+" attending manual class");

}

}


class HR{

public static void main(String[] args) {

System.out.println(" Program Starts........");

Student st = new DevStudent(); 

st.name = "Rahul";

st.id=123;

st.java();

if(st instanceof TestStudent){

TestStudent ts = (TestStudent)st;

ts.manual();

}

else{

System.out.println(" Sorry You can't attend Manual Class");

}

System.out.println(" Program Ends.....");


}

}


Output:

Program Starts........

Rahul attending java class

Sorry You can't attend Manual Class

Program Ends.....


No comments:

Post a Comment