Java Reference
In-Depth Information
Rule 1 says that a method declaration in the class takes priority. But D doesn't override hello; it
implements interface A. Consequently, it has a default method from interface A. Rule 2 says that
if there are no methods in the class or superclass, then the method with the most specific
default-providing interface is selected. The compiler therefore has the choice between the hello
method from interface A and the hello method from interface B. Because B is more specific, the
program will print “Hello from B” again. To check your understanding of the resolution rules,
try Quiz 9.2 .
Quiz 9.2: Remember the resolution rules
For this quiz, let's reuse the previous example except that D explicitly overrides the hello
method from A. What do you think will get printed?
public class D implements A{
void hello(){
System.out.println("Hello from D");
}
}
public class C extends D implements B, A {
public static void main(String... args) {
new C().hello();
}
}
Answer:
The program will print “Hello from D” because a method declaration from a superclass has
priority, as stated by rule 1.
Note that if D was declared as follows,
Search WWH ::




Custom Search