Interfaces as Contracts in Java
An interface specifies operations that implementing classes promise to provide. You use interfaces when different kinds of objects should support the same requests, even though they carry them out differently. In Java, an interface also acts as a type: a ticket checkout can request a price without depending on the particular class of ticket. These examples focus on ordinary public instance methods declared without bodies.
Read the contract
Consider a recreation centre that sells workshops and guided tours:
interface TicketPrice {
int credits();
}The declaration promises a method named credits, with no parameters, that returns an integer. Here, credits() is implicitly public and abstract: an implementing object must have a public method that supplies the required behaviour. Other forms of interface methods exist in Java, but this contract needs only this ordinary form.
The return type alone does not explain what the integer means. Documentation should also state that the result is the ticket's non-negative cost in credits. The compiler checks compatible declarations; it does not prove that a method obeys every rule written in a comment.
Supply an implementation
A concrete class declares the relationship using implements:
class Workshop implements TicketPrice {
public int credits() {
return 6;
}
public int durationMinutes() {
return 45;
}
}
class GuidedTour implements TicketPrice {
public int credits() {
return 10;
}
}Both classes provide the required operation. A class may have additional methods and its own instance fields; the interface does not require identical internal designs. A concrete class must supply, or inherit, implementations for its required abstract methods. It may also implement more than one interface.
The implementing method must be public. Writing int credits() without public gives the method more restrictive access and fails to fulfil this contract. Changing its parameters also creates a different method rather than supplying the required one. Merely having a matching method does not make an unrelated class implement the interface: the implementation relationship must be declared or inherited.
Use the interface type
An interface reference is a reference variable whose declared type is an interface. It can refer to an object of a class that implements that interface:
TicketPrice ticket = new Workshop();
int cost = ticket.credits();The object is still a Workshop. Assigning it to ticket does not create a new object or remove its methods. However, the declared reference type controls which methods the compiler permits you to call.
Question | What determines the answer? | Application |
|---|---|---|
Can you assign this object to the variable? | The declared implementation relationship | A Workshop can be assigned to TicketPrice |
Can you call this method through the variable? | Methods available through the declared type | ticket.credits() is permitted |
Which implementation runs? | The object's runtime class | Workshop.credits() runs |
The final distinction is called runtime dispatch. If you instead assign new GuidedTour() to ticket, the same expression ticket.credits() executes the guided tour's implementation.
Example: A checkout can add the results from a workshop and a guided tour through two TicketPrice references:
Each object supplies its own result. The checkout needs only the common operation, so another ticket class can join the system by implementing the same contract.
What to remember
- An interface declares a shared contract and can be used as a type.
- A concrete implementing class must fulfil the required method declarations.
- The reference type controls permitted calls; the object class selects the implementation.
- Interface compatibility does not prove that the implementation follows every documented behavioural rule.
Example: Recreation Activities Through One Interface
A recreation centre records activity prices in tokens. Its interface contract is the set of operations an implementing class promises to provide. Here, TokenCost requires a public method returning an activity's token cost. The following class declarations are separate from the client statements, which run inside a valid method.
interface TokenCost {
int tokens();
}
class Climbing implements TokenCost {
public int tokens() {
return 8;
}
}
class Skating implements TokenCost {
private int rounds;
public Skating(int rounds) {
this.rounds = rounds;
}
public int tokens() {
return 2 + 3 * rounds;
}
}
// Inside a method:
TokenCost first = new Climbing();
TokenCost second = new Skating(5);Skating costs 2 entry tokens plus 3 tokens per round. Climbing has a fixed price. Assume the supplied round counts are valid non-negative integers.
a) Explain why first.tokens() is permitted, identify the implementation that runs, and find its returned value.
The declared type of first is ________. That interface declares tokens(), so the compiler permits the call.
The assigned object was created with new Climbing(). Therefore, the call executes Climbing.tokens(), whose body returns the fixed activity price.
The call executes Climbing.tokens() and returns 8 tokens. The interface supplies the operation's declaration; the object's class supplies the method body.
b) Find the value returned by second.tokens() and distinguish the entry charge from the round charge.
The reference second points to a Skating object whose rounds field was initialized to 5. Its tokens() method therefore uses five rounds.
The round charge is ________, calculated from 3 tokens per round multiplied by 5 rounds. Add the separate entry charge of 2 tokens:
The call returns 17 tokens. Counting only the round charge would omit the entry charge that the implementation explicitly includes.
c) The client now executes the statements below. Find the final value of total and explain whether the declared type of first changes.
first = new Skating(4);
int total = first.tokens() + second.tokens();Reassignment makes first refer to a new Skating object with four rounds. The declared type of first remains TokenCost; only the referenced object changes. The separate reference second still points to its original five-round skating object.
For the new object, the round charge is ________, so the full cost returned through first is ________:
Add the two current method results:
The final total is 31 tokens, and first remains declared as TokenCost. Reassignment changes which implementation its next call reaches; it does not change the variable's declared type.
Match each Java keyword or method category to its role in an interface-based design. For extends, consider its use in an interface declaration.
Connects a class declaration to the contracts it promises to fulfil
Connects a child interface declaration to its parent contracts
An instance operation whose body is supplied within an interface
An operation declared without a body that a concrete implementing class must supply or inherit
abstract method
extends
default method
implements
A building-control program contains the following Java declarations. The variable declarations are inside a valid method. For each expression in the table, enter yes if it compiles and no if it does not. Consider each expression independently after the declarations.
interface Appliance {
void start();
}
class Fan implements Appliance {
public void start() { }
public void stop() { }
}
// Inside a method:
Appliance a = new Fan();
Fan f = new Fan();| Expression | Compiles: yes or no |
| a.start() | |
| a.stop() | |
| f.stop() | |
| new Appliance() |