Chapter FOUR
Interfaces


Exam Objectives

Develop code that declares, implements and/or extends interfaces and use the atOverride annotation.

Answers

1. The correct answer is C.
Since the method signature (method name plus parameter list) of aMethod() is the same in interface A and class Test, the compiler thinks the method in Test is overriding the default method. However, overriding a method includes the return type, which doesn't match (long vs. int).


2. The correct answer is C.
An interface method cannot be default and static at the same time. Therefore, a compile-time error is generated.


3. The correct answer is A.
There is nothing wrong with the code. The equals method is valid since it doesn't have the signature of Object's equals. The this keyword can be used inside the default method (it refers to the object that implements the interface) and because we are testing the same instance (q), the code returns true.


4. The correct answer is B.
If you want to call the default method of the super interface from the implementing class, you have to do it with the following syntax:

NameOfTheInteface.super.defaultMethod();

However, this only works with the most direct super interface. In the case of the example, interface E. If you try to use:

D.super.print();

The compiler would generate an error saying that you cannot bypass a more specific direct super type.


5. The correct answer is C.
Interface F defines a static method that should be used as:

F.test();

Since the type of variable q is F, you cannot use method test(). If the type of variable q were Question_4_5, the program would print Q test.

By the way, test() on Question_4_5 doesn't redefine test() on interface F, since static methods on interfaces are not inherited.


6. The correct answer is B.
In an inheritance hierarchy, the most specific method is the one called, which in this case, it's the one defined by Question_4_6.

If we remove method doIt() in class Question_4_6, the program would stop compiling, since the default method doIt() inherited from G will conflict with the method inherited from H (the compiler wouldn't know which one you intended to run).