Defining an interface Flashcards
Give the rules for defining an interface !
- Interfaces cannot be instantiated directly.
- An interface is not required to have any methods.
- An interface may not be marked as final.
- All top-level interfaces are assumed to have public or default access. Therefore, marking an interface as private, protected, or final will trigger a compiler error, since this is incompatible with these assumptions.
- All nondefault methods in an interface are assumed to have the modifiers abstract and public in their definition. Therefore, marking a method as private, protected, or final will trigger compiler errors as these are incompatible with the abstract and public keywords.
Give the declaration of an interface with methods that violate the rules !
private final interface CanCrawl { // DOES NOT COMPILE
private void dig(int depth); // DOES NOT COMPILE
protected abstract double depth(); // DOES NOT COMPILE
public final void surface(); // DOES NOT COMPILE
}
Explain how each member is violating the rules !
The first line doesn’t compile for two reasons :
First, it is marked as final, which cannot be applied to an interface since it conflicts with the assumed abstract keyword.
Next, it is marked as private, which conflicts with the public or
default required access for interfaces
The second and third line do not compile because all interface methods are assumed to be public and marking them as private or protected throws a compiler error
Finally, the last line doesn’t compile because the method is marked as final and since interface methods are assumed to be abstract, the compiler throws an exception for using both abstract and final keywords on a method.