Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my object cast to interface not calling default method? [duplicate]

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.

like image 892
abhivemp Avatar asked Oct 22 '25 17:10

abhivemp


2 Answers

The whole point of inheritance and polymorphing is that it doesn't matter what type the variable has, the actual type of the created object determines which method will be called.

There is no way for you to call the Vehicle version of the canFly method, since it has been overridden by the Car class, and the real object is a Car.

like image 104
Andreas Avatar answered Oct 25 '25 08:10

Andreas


The Lambda faq lists conflict resolution rules for default methods. First rule is:

Classes always win. A declaration in the class or a superclass takes priority over any default method declaration.

Because the class provides an implementation of the method, that always takes precedence over the default method on the interface. ("Default" means a fallback for cases where no implementation is provided otherwise.)

Casting only keeps the compiler from reporting an error due to some variable's type not matching the type of the thing being assigned to it. It's there for cases where you know it's ok to treat something as another type and you need to overrule the compiler. Casting has no effect at runtime, except to cause a ClassCastException to be thrown if the cast is erroneous. See here for more details.

TLDR: The idea that you could use casts to change what method gets called is not accurate.

like image 45
Nathan Hughes Avatar answered Oct 25 '25 07:10

Nathan Hughes