I am learning more about polymorphism and casting in Java. I was running some code and I am quite confused with the output. I would really appreciate it if someone can explain what the compiler is doing here.
When I wrote this code, I thought that since newCar()
is being cast to Vehicle
, I assumed it would use the default method that was written in the Vehicle interface. But it looks like it used the overridden method in Car.
Thanks in advance!!
public interface Vehicle {
default boolean canFly() {return true;}
}
public class Car implements Vehicle {
boolean canFly() {return false;}
public static void main(String[] args) {
Vehicle vehicle = (Vehicle) new Car();
System.out.println(vehicle.canFly());
}
}
I saw possible duplicates; however, the question was targeted to only classes. My question is specifically with interfaces.