Java inheritance downcast ClassCastException

后端 未结 6 1372
走了就别回头了
走了就别回头了 2021-01-22 17:10

given the following code, I have a question:

class A{}
class B extends A {}
class C extends B{}

public class Test {
    public static void main(String[] args) {         


        
6条回答
  •  被撕碎了的回忆
    2021-01-22 17:26

    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.

提交回复
热议问题