I was testing out covariant return types and came across this problem.
class Vehicle {
int i = 3;
}
class Car extends Vehicle{
int i = 5;
public Car returningCar(){
System.out.println("Returning Car");
return new Car();
}
public Vehicle returningCarInVehicle(){
System.out.println("Returning CarInVehicle");
return new Car();
}
}
public class ScjpTest{
public static void main(String[] args){
Car car = new Car();
Vehicle vehicleCar = car.returningCar();
Vehicle vehicleCar2 = car.returningCarInVehicle();
System.out.println("vehicleCar " + vehicleCar.i);
System.out.println("vehicleCar2 " + vehicleCar2.i);
}
}
The output to the above is Returning Car
Returning
CarInVehicle
vehicleCar 3
vehicleCar2 3
I dont understand why the output is 3. I was expecting the output to be 5 in both instances because at runtime the JVM uses the actual object not the reference.
Thanks
Fields aren’t virtual/overrideable/etc. They will be resolved according to the compile-time type of the reference, which in this case is
Vehicle.This code would print “vehicleCar2 5”:
since the cast makes the expression of compile-time type
Car.