Java inheritance downcast ClassCastException

泄露秘密 提交于 2019-12-02 00:51:51

All B's are A's, by inheritance. But not all A's are B's. This particular instance isn't, hence the runtime exception.

You are trying to cast a super class reference variable to a sub class type. You cannot do this. Think practical, a super class object cannot contain independent methods (other than the super class' methods) of the sub class.

At run-time you might call a method in the sub class which is certainly not in the super class object.

class A{
  public void foo(){}
}
class B extends A {
  public void bar(){}
}

Now,

A a=new A();
B b=(B)a;
b.bar();

When you call like this the compiler, will only check whether the method bar() existed in the class B. That's it. It doesn't care about what is in the 'object' because it is created at runtime.

But at runtime, as said before there is no bar() method in the object a. b is just a reference that is pointing to object a but a contains only foo() not bar()

Hope you understood. Thank you.

Downcasts are illegal. An A is not a B and therefore you can't cast it to be one. You can cast B to be A, but not the other way round.

In your code example, the variable a is a reference to an object of type A. The class B extends the class B, but the relationship between classes A and B can only be described as follows:

  1. Class B isa Class A (every object of type B can legally be cast to class A).
  2. Class A is-not-a Class B (you can never assign an rvalue of type B to a reference of type A).

This is legal: a = (A)b; because class B isa class A.

One way to think of it is class B is a superset of class A.

If A is a set that contains (1, 2) and B is a set that contains (1, 2, 3) then B is a superset of A (in java terms: B can be cast to A) but A is not a superset of B (A can not be cast to B).

From a different point of view:

  • Socrates was mortal.
  • All men are mortal.

Socrates (class B) isa man (class A).

This is an invalid minor assertion: All men are Socrates.

Remember that legal casts are ruled by the "IS-A" test, why you can compile your code?, because ClassCastException is an Unchecked Exception, since extends from RuntimeException

ClassCastException ---IS-A--> RuntimeException (Another example of a possible legal cast).

user11949964

To downcast in Java, and avoid run-time exceptions, use the following code.

if (animal instanceof Dog) {
  Dog dogObject = (Dog) animal;
}

Animal is the parent class and Dog is the child class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!