I have a question that I could not find the answer to. Let's say we have the following code in java or C #:
class Car {
}
And then in Java
class Truck extends Car {
}
and c #
class Truck : Car {
}
In C #, the following works fine:
List<Car> carList = new List<Car>();
foreach(Truck t in carList)
This works because Truck is a subclass of Car, which in simple terms means that each Truck is also a car. The fact is that a check of this type is performed, and only cars are selected from carList.
If we try the same thing in Java:
List<Car> carList = new ArrayList<Car>();
for(Truck t : carList)
Because of the code inside the extended loop, the code does not even compile. Instead, we should do something similar to get the same effect:
for(Car t : carList)
if(t instanceof Car)
//cast t to Truck and do truck stuff with it
This is the same idea that works without problems in C #, but in Java you need additional code. Even the syntax is almost the same! Is there a reason why this does not work in Java?