7. Java 8: Method Enhancements Flashcards

1
Q

Java 8 now supports two new method types for interfaces, what are these?

A

Static methods

Default methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
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();

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a default method in a interface?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
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.

A

Greeter.super.greet();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
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{
}
A

Compilation fails.

GreeterImpl should provide a override for the method greet because two defaults are found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between a default method inside a interface and a regular method inside a class?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
What is the result of the following:
public interface MyInterface {
default boolean equals(Object o) {
return true;
}
}
A

Won’t compile.

You cannot use default methods to override any of the Object methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly