How do arrays “remember” their types in Java?

前端 未结 5 580
情深已故
情深已故 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:08

    1. Simply speaking: arrays are a class. BB[] does not extend AA[] even though BB extends AA.
    2. In the early days pre-generics. ArrayLists held Objects. so anything could be held in an ArrayList. If you had an Array of Object, you could play the same game. Now with generics you can specify an ArrayList with a specific type like ArrayList.
    3. actually the problem is on line 2:

      AA[] arr2=arr;
      

    Let's make the problem a little easier. You have a vehicle class and a bike and a car class that extends vehicle. You can not have

    Bike b=new Bike()
    Car c=b;
    

    arr2 is an array and arr is an array, but the class is different. Does that help?

提交回复
热议问题