Defining an interface Flashcards

1
Q

Give the rules for defining an interface !

A
  1. Interfaces cannot be instantiated directly.
  2. An interface is not required to have any methods.
  3. An interface may not be marked as final.
  4. 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.
  5. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give the declaration of an interface with methods that violate the rules !

A

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
}

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

Explain how each member is violating the rules !

A

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.

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