How do arrays “remember” their types in Java?

前端 未结 5 521
情深已故
情深已故 2021-02-07 02:14

Consider the following code:

class AA { }

class BB extends AA { }

public class Testing {

    public static void main(String[] args) {
        BB[] arr = new B         


        
5条回答
  •  星月不相逢
    2021-02-07 03:05

    3) Whether you do AA a = new AA(); or AA a = new BB();, the compiler does not remember later what you assigned to a, only that its declared type is AA. However, in the latter case, you can in fact assign the value of a to an element of a BB[], so arr2[0] = a; should not give you a runtime exception. Thus, the compiler cannot tell in advance. (Besides, you could try nasty things to change the value of a at runtime between the respective lines...)

    2) Had you used List listAA = listBB;, you would have gotten a compile error. So what you expected from the array example -- compile time detection of an arising impossible assignment -- in fact works with lists! If you leave out the generic type parameter, however, you will get a raw-type list, to which you can assign other lists without reasonable type checks. This is best considered a leftover from early Java, which should be avoided. If you added the following line below you question's code:

    BB item = listBB.get(0);
    

    Do you think it should/will compile? Should/will it run (and, if so, what should be its result)?

    The how part of 1) probably warrants a separate question.

提交回复
热议问题