public interface Pet { // Pet Interface
default void introduce() {
System.out.println("Interface");
}
}
abstract public class Animal {
public void introduce() {
System.out.println("Animal class");
}
}
public class Dog extends Animal implements Pet{}
Now when I called the introduce
method on Dog
, what actually happens?
default methods are always 'last in line'. If any method anywhere in the hierarchy of the chain of classes (so, here, 'Dog' at the top, then Animal, then Object - those are the classes involved in the hierarchy) matches, that always wins.
Only if zero methods are found in the entire class chain, and the interface chain contains exactly 1 method with a default implementation - then that one is chosen instead. If there are more than one, then your code won't compile (if you have class A implements B, C {}
and both B
and C
have the same method defined and both have a default impl, then you can't compile A without explicitly writing that method into A.