Interfaces
The interface as a method contract in Java: implements, several interfaces for one class, interface-typed variable, choosing between an interface and an abstract class, default method.
- 19 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Interface: what is it?
Show the answer
A list of method signatures that a class commits to provide, without imposing how and without requiring a family link.
It describes what an object can do, not what it is. A variable of its type can refer to any object whose class fulfils it.
This class is rejected with
Plane is not abstract and does not override abstract method land() in Flyer. Which fix is right?
```java
interface Flyer {
void takeOff();
void land();
}
class Plane implements Flyer {
public void takeOff() { System.out.println("runway"); }
}`- Add
public void land() { … }to Plane - Add
void land() { … }withoutpublicto Plane - Add
extends Flyerto the Plane class - Declare
land()asprivatein Plane
Show the answer
Add
public void land() { … }to PlaneTo implement is to provide every method of the contract, public as in the interface. Without
public, or withprivate, visibility is weaker: rejected. Andextendsdoes not apply to an interface from a class.- Add
A class declares that it fulfils a contract with …; it can fulfil …, separated by commas.
Show the answer
A class declares that it fulfils a contract with implements; it can fulfil several, separated by commas.
That is how single inheritance is worked around:
class Duck extends Animal implements Flyer, Swimmertakes one class and two contracts.Contract: what is it?
Show the answer
A class's commitment to those who use it: the methods it provides, whatever the way it carries them out.
Code that uses the contract depends only on it, not on the concrete classes: one can be changed without touching the other.
A method
launch(Flyer f)must accept Bird, which already inherits from Animal, Plane, which inherits from Machine, and Drone. What should Flyer be?- An interface that the three classes implement
- An abstract class that the three classes inherit from
- A class that inherits from both Animal and Machine
- Nothing: write three
launchmethods with no link between them
Show the answer
An interface that the three classes implement
Bird and Plane already have a parent class and Java allows only one
extends. An interface, which can be combined, gives the shared capability to unrelated classes, and a singlelaunchsuffices.