1

I'm a beginner in Java and I was playing with some Java code. However I couldn't sort out why is it giving runtime error when I assign the reference of a parent class object to a child class variable. I've done explicit typecasting too. Is there any way possible to resolve it?

class Employee{
    int e;//creating empty class
}

class Teacher extends Employee{
    int f;//creating empty class
}

class run{
    public static void main(String args[]){
        Employee e;
        e= new Employee();
        Teacher t;
        t= (Teacher)e; //giving runtime error
    }
}
maloomeister
  • 2,461
  • 1
  • 12
  • 21

2 Answers2

2

We can assign child class object to parent class reference variable but we can't assign parent class object to child class reference variable.

2

A Teacher is an Employee, but not every Employee is a Teacher.

So, an Employee variable can hold objects of type Employee itself, as well as its subclasses like Teacher, Worker or whatever. But if you have a Teacher variable, it can only hold Teacher instances (and subclasses of Teacher), but not Employee or Worker instances.

With

t = (Teacher) e;

you have e, an Employee variable. Generally, this e does not "fit into" a Teacher variable, only in the possible case that the Employee variable e holds an Employee subclass instance, namely a Teacher instance.

So, without the cast, the compiler forbids the assignment. Writing the cast, you as developer tell the compiler

Hey, I know that generally the assignment isn't allowed, but I promise that, at runtime, the instance in e will be a Teacher. So, please compile that line of code despite the risk, and give me an exception at runtime if my promise doesn't hold.

And that's what happens.

Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7