Clarification On TypeCasting of ArrayList in Java
I need a clarification regarding the below code.
1. ArrayList<Car> myCar = new ArrayList<Car>(); // Car is a java class which extends
// Vehicle class[/b]
2. ArrayList<Bus> myBus = new ArrayList<Bus>(); // Bus is a java class which
//extends Vehicle class
3. myCar.add(new Car("test"));
4. ArrayList d = myCar;
5. myBus = (ArrayList<Bus>)d;
In line 5., we observe that the ArrayList d is able to be typecasted to another form of ArrayList<Bus>. I am not clear on this as if we consider the below scenario, the typecasting is not possible. Can anybody please suggest me on this..!
Car myCar = new Car();
Bus myBus = new Bus();
Car car1 = (Car)myBus; // It will not compile as it cannot typecast this..!