
Java
Consider an example in Java programming language:
class Person{
String getName(){ return "Fred"; }
}
class Employee extends Person {
double getSalary(){ return 57; }
}
public class X {
public static void main(String args[])
{
Person p = new Person();
Employee e = (Employee) p; //This causes a Java.lang.ClassCastException
System.out.println(e.getSalary());
}
}
When this program runs, It crams a Person p object into an Employee e object which causes a "Java.lang.ClassCastException: Person cannot be cast to Employee"
Employee e = (Employee) p; //error happens here
Note that an Employee has a method called getSalary, but Person does not. Not all People have Salaries. The Person object is Instantiated and put into 'p'. The problem is that this particular person p is not an employee. If that person p WAS an employee the code would run correctly and print 57.
Casting a superclass reference to a subclass is dangerous because sometimes the cast will work perfectly, and sometimes it will crash the program. The cast itself is the dangerous part. When doing casts of this sort, the programmer needs to make 100% sure that this Person p was instantiated with a new Employee(). Then the Person object will have the method getSalary().
This code is dangerous as well, but it does not throw any exceptions, it makes a Person which is an Employee, and then casts that Person/Employee into an Employee type.
class Person{
String getName(){ return "Fred"; }
}
class Employee extends Person {
double getSalary(){ return 57; }
}
public class X {
public static void main(String args[]){
Employee x = new Employee();
Person w = (Employee) x;
Employee y = (Employee)w;
System.out.println(y.getSalary());
}
}
Here, employee x is created and then cast into a Person object. Person w is an Employee. Now when we cast the Person w into Employee y, everything is fine, and the program prints "57.0". It's dangerous because this person might not have been an Employee.
Copyright © 2026 eLLeNow.com All Rights Reserved.