A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
package com.training.exceptions;
class Vehicle {
public void doStuff() {
System.out.println("Vehicle");
}
}
class Car extends Vehicle{
public void doStuff() {
System.out.println("Car");
}
}
class Bike extends Vehicle {
public void doStuff() {
System.out.println("bike");
}
}
public class ClassCast {
public static void main(String[] args) {
try {
// this will throw a ClassCastException
Vehicle v = (Bike)new Vehicle();
v.doStuff();
}catch(ClassCastException cce) {
System.err.println("Class Cast Exception has been caught, check your code again");
cce.printStackTrace();
}
}
}
Output:
Class Cast Exception has been caught, check your code again
java.lang.ClassCastException: com.training.inheritance.Vehicle
at com.training.inheritance.VehicleTest.main(VehicleTest.java:30)
No comments:
Post a Comment