7. Java 8: Method Enhancements Flashcards
Java 8 now supports two new method types for interfaces, what are these?
Static methods
Default methods
Considering the following class, what is the result: public interface DoAble { public static void doStuff() { System.out.println("hello"); } }
public class Task implements DoAble {}
new Task().doStuff();
Compiler error
Normally you can reference static methods using a object reference. Static methods for interface however can only be called using a Class reference to the interface. So the only valled call to doStuff() in this example is: DoAble.doStuff();
What is a default method in a interface?
A interface can now provide a default implementation for methods. This way any implementing classes are not required to implement all of the methods (only the non-default ones).
Given the following interface and class: interface Greeter { default void greet() { System.out.prinltn("hello"); } } class GreeterImpl implements Greeter{ void greet() { // 1 } }
Replace line 1 to call the default method from the interface.
Greeter.super.greet();
What is the result of the following: interface Greeter { default void greet() { System.out.prinltn("hello"); } } interface Greeter2 { default void greet() { System.out.prinltn("hello"); } } class GreeterImpl implements Greeter, Greeter2{ }
Compilation fails.
GreeterImpl should provide a override for the method greet because two defaults are found.
What is the difference between a default method inside a interface and a regular method inside a class?
A default method can only access the arguments and not any instance methods or variables (because an interface itself doesn’t have any instance methods or variables.
What is the result of the following: public interface MyInterface { default boolean equals(Object o) { return true; } }
Won’t compile.
You cannot use default methods to override any of the Object methods.