Concepts / Defining an Interface

Defining an Interface

A class implements an interface by using the reserved word implements in its header and by defining every instance method the interface declares.

  • Programming

Why Drawing Code Needs a Guarantee

Imagine a drawing program where many different shapes need to be painted onto a screen. The drawing code wants to say, simply, stroke this shape with a pen. It does not care whether the shape is a circle, a polygon, or a piece of text. What it needs is a guarantee that every shape it receives knows how to be stroked. Java gives you a construct for writing down that guarantee without writing any of the drawing logic itself. That construct is called an interface.

This article focuses on one question: what does an interface actually contain, and what rules govern the things placed inside it? As you read, keep one idea in mind. The interface describes a promise, and a class is the thing that keeps it.

What an Interface Declares

Definition

A Java interface is a reserved word that introduces a set of instance method declarations with no implementations. A declaration gives a method's name, its parameters, and its return type. An implementation supplies the body that actually does the work. The interface gives only the declarations.

The word interface is a reserved word in Java. The language reserves it for a specific purpose, so you cannot use it as an ordinary name. The interface lists method headers without giving their bodies, which leaves a gap. Something has to fill that gap, and in this article the gap is filled by a class: the class that implements the interface.

java
Notes on the code
  • The keyword interface opens the definition, and Strokeable is the name chosen for it.
  • The single declaration stroke accepts one Graphics parameter.
  • The semicolon ends the declaration. There is no curly-brace body because the interface does not provide one.

Reading the Strokeable Declaration

Read the example from the outside in. The keyword interface opens the definition. Inside the braces sits one declaration, stroke, which accepts one Graphics parameter. Notice the semicolon at the end. The declaration has no body, and that is deliberate. The body belongs to whichever class eventually implements Strokeable.

Predicting the Missing Method

Before reading the rule, make your own prediction. Suppose a class declares that it implements Strokeable, but the class leaves out any code for the stroke method. Think about what the interface promises and what the class has agreed to.

What do you think happens?

A class declares that it implements Strokeable but has no stroke method. Does it meet the interface's requirements?

  • Yes, the implements clause is enough on its own

  • No, the class has not provided the method the interface declares

  • Yes, because stroke is optional in an interface

Reveal answer
Answer:

No, the class has not provided the method the interface declares

The source states that omitting either the implements clause or the method implementations means the class does not meet the interface's requirements. The interface promises stroke, and the class must supply it.

The Class Header and Its Promise

The class header is the line that names the interface the class is promising to satisfy. The reserved word implements carries that promise. The class body then holds the required method together with whatever else the class needs. The source shows the general form of this arrangement, with the body abbreviated and the three dots standing for other members the class may also contain.

java
Notes on the code
  • The header names Strokeable, which is the promise.
  • The stroke method is the one the interface requires.
  • The three dots stand for other members the class may also contain.

Because the class carries the promise, every object created from it carries the promise too. The source defines it this way: an object implements an interface if it belongs to a class that implements that interface. That is why any object of type Line implements Strokeable, and why a Line object carries the stroke() method.

One Superclass, Several Interfaces

The source contrasts two limits directly. A class is limited to extending one other class, but it has no stated limit on how many interfaces it implements. A header can therefore combine one extends clause with a list of implements names. The source gives the header FilledCircle extends Circle implements Strokeable, Fillable as a valid example. Here FilledCircle inherits from Circle and promises to satisfy both Strokeable and Fillable.

FilledCirclethe class being declaredCirclesingle superclassStrokeableinterface promiseFillableinterface promiseextendsimplementsimplements
Which parts of a class header link it to its single superclass, and which link it to each interface? The superclass link uses extends and appears once. The interface links use implements and can appear several times.

The Two Requirements a Class Must Meet

The source is explicit that writing the methods is not enough by itself. A class has to meet two separate conditions. The first is the implements clause in the class header, which states the promise. The second is the method implementations, which means the class defines every instance method the interface declares. Each condition does a different job. Omitting either one means the class does not meet the interface's requirements.

Implementing aninterfaceimplements clauserequirement oneInterface metEvery instance methoddefinedrequirement twoClass fails theinterfacerequiresrequiresboth metboth meteither missingeither missing
How do the implements clause and the defined-methods requirement combine? If both are satisfied the class meets the interface. If either one is missing, the class fails to meet it.

Tracing a Class With No stroke Method

Worked example

Following a broken implementation from header to error

A class is declared with the header class Dot implements Strokeable, but its body contains no stroke method. Where does the program break?

  1. 1
    Start at the interface

    Strokeable declares one method, stroke, which takes a Graphics parameter.

  2. 2
    Check the header

    The implements Strokeable clause is present, so requirement one is met.

  3. 3
    Check each declared method

    Ask whether each declared method has a matching implementation in the class. stroke has none.

  4. 4
    Find the first failure

    The comparison first fails at the missing stroke method. That is the divergence point, and the class does not meet the interface.

Result

The program breaks at the class body, where the required stroke method should be but is absent. The class claims Strokeable, but it does not satisfy it.

Header implementsStrokeablestroke defined?Class meets interfaceClass rejectedcheck each methodyesno
When a class declares implements but is missing a required method, at which check does the failure appear, and what path does the check follow from the header to the error?

The source recommends walking forward from the interface declaration. Ask whether each declared method has a matching implementation, and whether each constant is being used rather than redefined. The place where that comparison first fails is usually the place to look. Everything after that point may look wrong only because the early mismatch carried forward.

What an Interface Can Hold

An interface can hold two kinds of members. Method declarations describe behavior that implementing classes must supply. Variable declarations describe fixed values that implementing classes receive. The method branch carries an obligation: every implementing class must provide a body for each method. The variable branch carries a gift: every implementing class can use the variable without declaring it again.

java
Notes on the code
  • The declaration is a fixed value shared by every implementing class.
  • The constant name uses underscores, the usual Java convention for constants.

The three declarations above act as constants in everyday terms: each name is tied to one fixed number. The interface works as a container with a method branch and a variable branch. Keeping these two effects separate in your mind is the key to reading interfaces correctly.

Required, Optional, and Implied Modifiers

Modifiers in an interface follow fixed rules. Every method declared in an interface must be public and abstract, and the source states this explicitly. Variables in an interface are public, static, and final. Because these are the only options available in each case, Java does not require you to write the modifiers. Writing or omitting them changes how the text reads, not what the interface requires.

ItemModifierStatus in an interface
Interface methodpublicImplied; may be omitted
Interface methodabstractImplied; may be omitted
Interface variablepublicImplied; may be omitted
Interface variablestaticImplied; may be omitted
Interface variablefinalImplied; may be omitted
Interface method declarationsemicolon, no bodyRequired
Class headerimplementsRequired to declare the promise
Implementing classmethod body for each declared methodRequired

Modifiers and required parts for interface members and implementing classes, as stated in the source.

Mistakes Beginners Make with Interfaces

  • Common mistake

    Writing the methods but leaving out implements

    What it looks like
    class Line { public void stroke(Graphics g) { } }
    Why it fails

    The class body is correct, but the header makes no promise. The source requires both the implements clause and the method implementations.

    Do this instead
    class Line implements Strokeable { public void stroke(Graphics g) { } }
  • Common mistake

    Writing the implements clause but leaving out the method

    What it looks like
    class Line implements Strokeable { }
    Why it fails

    The header makes the promise, but the class does not supply stroke. The class does not meet the interface.

    Do this instead

    Define every instance method the interface declares inside the class body.

  • Common mistake

    Adding a body to the interface method

    What it looks like
    interface Strokeable { void stroke(Graphics g) { } }
    Why it fails

    An interface gives declarations only. The body belongs to the implementing class.

    Do this instead
    interface Strokeable { void stroke(Graphics g); }
  • Common mistake

    Believing an extends clause can list several superclasses

    Why it fails

    A class can extend one other class but may implement any number of interfaces.

    Do this instead

    Use one extends clause and as many names as needed after implements.

  • Common mistake

    Treating interface variables as ordinary instance fields that each class may redefine

Practice: Finding the Break

MEDIUM

A class is declared as class FilledCircle extends Circle implements Strokeable, Fillable. It defines stroke correctly but has no method that Fillable declares. Using the two requirements, say which requirement fails, and identify the first place in the code where a comparison against the interface breaks.

Hints
  • Check the header first. Does it name both interfaces with implements?
  • Then walk the methods declared by Fillable and ask whether each has a matching implementation in FilledCircle.
  • The extends clause is about the superclass, so it does not satisfy either interface.

Key Takeaways

  • A class implements an interface by naming it with the reserved word implements in its header and by defining every instance method the interface declares. Both requirements must be met.
  • An interface holds method declarations with no bodies and may also hold variables. Methods are public and abstract, and variables are public static final, so those modifiers may be omitted.
  • A class can extend one other class and implement any number of interfaces, as in FilledCircle extends Circle implements Strokeable, Fillable.
  • When a class fails an interface, trace forward from the interface declaration and find the first comparison that fails. That point is where the divergence begins.