Complete the code to declare a default method in an interface.
public interface MyInterface {
default void [1]() {
System.out.println("Default method");
}
}The method name should be defaultMethod. The keyword default is already used before the return type.
Complete the code to call the default method from an interface inside a class.
public class MyClass implements MyInterface { public void callDefault() { [1].super.defaultMethod(); } }
To call a default method from an interface, use InterfaceName.super.methodName(). Here, MyInterface.defaultMethod() is incorrect; it should be MyInterface.super.defaultMethod(), but since the blank is before the dot, the correct choice is MyInterface to complete the call.
Fix the error in the code to correctly override a default method in a class.
public class MyClass implements MyInterface { @Override public void [1]() { System.out.println("Overridden method"); } }
The method name must exactly match the default method name in the interface, which is defaultMethod with correct case.
Fill both blanks to define a default method with a return type and a return statement.
public interface Calculator {
default int [1](int a, int b) {
return a [2] b;
}
}The method name is add and the operator to add two numbers is +.
Fill all three blanks to implement a default method that checks if a number is even.
public interface NumberCheck {
default boolean [1](int num) {
return num [2] 2 [3] 0;
}
}The method name is isEven. The modulo operator % checks the remainder, and == compares it to zero to determine evenness.