Casting and inheritance in Java

Consider this simple code:

class A {}

class B extends A {}

public class TestClass {
    public static void main(String args[]) {
        A[] a, a1;
        B[] b;
        a = new A[10];
        a1 = a;
        b = new B[20];
        a = b; // 1
        b = (B[]) a; // 2
        b = (B[]) a1; // 3
    }
}

Look carefully at the lines that I commented on 1,2 and 3. Line 1 will be resolved at compile time, since assignment is from a subclass link to a superclass link.

Casting to line 2 is necessary because the superclass reference is applied to the subclass reference variable. And this works at runtime because the object referenced by a is actually an array from B (line 1).

Now, here's where my confusion lies: line 3 will throw java.lang.ClassCastException. Now this means that at runtime, the program understands that the actual object is not an array of B, but an array of A.

, . B A? , B IS-A A, ? , 3 - ?

+4
3

a1 - A. B extends A, B A, A B. C, A a1. B.

A B.

+7

, , .

:

    A[] aa = new A[0];
    B[] bb = new B[0];

    System.out.println(aa.getClass());
    System.out.println(bb.getClass());

    System.out.println(aa.getClass().isAssignableFrom(bb.getClass()));
    System.out.println(bb.getClass().isAssignableFrom(aa.getClass()));

:

class [Lstuff.small.Try47$A;
class [Lstuff.small.Try47$B;
true
false

, A [] B [], .

+2

You are right in saying β€œB IS-A A,” and that is why i) There is no problem setting a = b;
ii) There is no problem during compilation for statement # 3.

But you cannot say "AA B", therefore a runtime exception.

0
source

Source: https://habr.com/ru/post/1668364/


All Articles