Concepts / Implementing Interfaces in Java

Implementing Interfaces in Java

A Java interface is a reserved word that introduces a set of instance method declarations with no implementations.

  • Programming

Why a Drawing Program 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. The word interface is reserved, which means the language sets it aside for this specific purpose and you cannot use it as an ordinary name.

The difference between a declaration and an implementation is the central idea here. A declaration gives a method's name, its parameters, and its return type. An implementation supplies the body that actually does the work. An interface gives only the declarations. Its methods end in a semicolon instead of a block of code, because the interface does not provide a body. The body belongs to whichever class eventually implements the interface.

java
Notes on the code
  • The keyword interface opens the definition, and Strokeable is the name chosen for it
  • stroke is a single method declaration that accepts one Graphics parameter
  • The semicolon replaces a body: the interface provides no implementation

What do you think happens?

Suppose a class declares that it implements Strokeable, but leaves out any code for the stroke method. Does the class meet the interface's requirements?

Reveal answer
Answer:

No. The class does not meet the interface's requirements.

The interface promises that every implementing class defines each method it declares. A class that omits stroke has broken that promise, even though its header names the interface.

Interface Methods as Obligations and Constants as Gifts

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

Strokeableinterfacestroke(Graphics g)method declarationImplementing classmust supply a bodyobligationINCHES_PER_FOOT = 12variable declarationImplementing classcan use the constantgiftdeclaresrequiresdeclaresshares
Which parts of an interface create an obligation for an implementing class, and which parts provide a shared value?

The diagram shows the two effects side by side. The interface sits at the top, one branch holds a method declaration that creates an obligation, and the other branch holds a constant that every implementing class can use. Keeping these two effects separate in your mind is the key to reading interfaces correctly.

Required, Optional, and Implied Modifiers

Modifiers are the keywords that appear before a method or variable, such as public or static. In an interface, some of these keywords are required by the rules, some can be omitted, and some are supplied by Java automatically. Sorting them into these three groups tells you exactly what the page is saying and what the compiler will assume.

MemberModifiers the rules requireWritten in the sourceWhat Java assumes
Method in an interfaceMust be public and abstractMay be omittedPublic and abstract even when the keywords are missing
Variable in an interfaceMust be public, static, and finalMay be omittedPublic static final, so each one is a fixed shared value

Modifiers for interface members. The rules fix these modifiers, so writing them is optional.

java
Notes on the code
  • The constant needs no written public static final because Java assumes them
  • The underscores in the name follow the usual Java convention for constants

Writing the Class Header with implements

A class implements an interface by using the reserved word implements in its header and by defining every instance method the interface declares. The header is the line that names the interface the class is promising to satisfy. Before reading the class body, the header tells you which promise is being made.

java
Notes on the code
  • implements Strokeable in the header states the promise
  • The stroke method in the body is the one the interface requires
  • The remaining members are whatever else the class needs
classkeyword that opens theclassFilledCircleclass nameextends Circleone superclassimplementsStrokeable, Fillableany number of interfaces
Where the class name, the extends clause, and the implements clause sit in one declaration line.

Two Conditions a Class Must Meet

Writing the methods is not enough by itself, and writing the implements clause is not enough by itself either. The source is explicit that a class has to meet two separate conditions. The first is the implements clause in the class header, which names the interface. The second is the class body, which must define every instance method the interface declares. Both conditions are required, and omitting either one means the class does not meet the interface's requirements.

Class headernames the interface withimplementsimplements clausepresent?Class bodydefines every declaredmethodstroke defined?Meets the interfaceRequirement not metcompiler reports an erroryesnoyesno
Which check does a class have to pass, and what happens when the interface's method is missing from the class body?

The two conditions do different jobs. The header makes the promise visible: it tells every reader and the compiler which interface the class claims to satisfy. The body fulfills the promise by supplying the actual method code. A header without a body is a promise with nothing behind it, and a body without the header is working code that never declares itself as an implementation of the interface.

Tracing a Missing Method

Worked example

Following a class that breaks its promise

A programmer writes a class Dot that declares it implements Strokeable but forgets to write the stroke method. Where does the program first depart from what the interface promised?

  1. 1
    Start at the interface

    Strokeable declares stroke(Graphics g) and promises that implementing classes will define it.

  2. 2
    Read the class header

    class Dot implements Strokeable names the interface, so Dot has taken on the promise.

  3. 3
    Walk forward to the body

    Compare each declared method with the matching implementation in Dot. The body has no stroke method, so the comparison fails here.

  4. 4
    Locate the divergence

    The first point where the comparison fails is the class body of Dot. Any later complaint about Dot or code that uses it is a consequence of this missing method.

Result

The program breaks at Dot's class body, because the header promises stroke but the body does not supply it. The fix is to define stroke in Dot.

Before
class Dot implements Strokeable {
    // no stroke method
}

The header promises Strokeable but the body is missing stroke, so the class does not meet the interface.

After
class Dot implements Strokeable {
    public void stroke(Graphics g) {
        // draw a single point using g
    }
}

The body defines stroke, so both conditions are met and Dot counts as implementing Strokeable.

Extending One Class and Implementing Many Interfaces

A class can extend one other class and implement any number of interfaces. The source contrasts these two limits directly: a class is limited to extending one other class, but it has no stated limit on how many interfaces it implements. Putting the two side by side makes the asymmetry easy to check.

java
Notes on the code
  • extends Circle appears once, because a class has one superclass
  • implements Strokeable, Fillable lists two interfaces separated by a comma
  • Each method declared by either interface must be defined in the body
CirclesuperclassFilledCirclethe class being declaredStrokeableinterfaceFillableinterfaceextendsimplementsimplements
How does FilledCircle relate to its single superclass and to each interface it implements?

The diagram shows where an error can come from. The extends relationship has a single target, so a class with two superclasses is not a valid header. The implements relationships can point to several interfaces, and each of them adds its own list of methods that the body must define. When FilledCircle fails to compile, locate the relationship responsible: if the header is wrong, look at the extends or implements clause; if the body is wrong, check whether every method from every listed interface is defined.

What do you think happens?

Can any object created from Line implement Strokeable, and why?

Reveal answer
Answer:

Yes, when Line is a class that implements Strokeable and defines stroke.

An object implements an interface if it belongs to a class that implements that interface. Because Line carries the promise, every object created from it carries the promise too, which is why a Line object carries the stroke method.

Mistakes Beginners Make with Interfaces

  • Common mistake

    Writing a body for an interface method

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

    An interface provides declarations with no implementations. The body belongs to the implementing class.

    Do this instead

    Write void stroke(Graphics g); with a semicolon, and put the body in each implementing class.

  • Common mistake

    Assuming the header alone is enough

    What it looks like
    class Dot implements Strokeable { } with no stroke method
    Why it fails

    The class must meet two conditions. The implements clause is only one of them.

    Do this instead

    Define every method the interface declares in the class body.

  • Common mistake

    Thinking omitted modifiers mean something different

    What it looks like

    Believing void stroke(Graphics g); in an interface is not public

    Why it fails

    Interface methods are public and abstract whether or not the keywords are written.

    Do this instead

    Read the omitted keywords as present and expect the same rule.

  • Common mistake

    Redefining a constant inside the implementing class

    Why it fails

    Interface variables are public static final and are already shared with every implementing class.

    Do this instead

    Use INCHES_PER_FOOT directly, without declaring it again in the class.

  • Common mistake

    Writing extends with more than one superclass

Practice: Find Where the Promise Breaks

EASY

A class is written as class Square implements Strokeable, Fillable, and its body defines stroke but not fill. Trace the program from the interfaces to the class body. Which requirement is not met, and at which line does the mismatch first appear?

Hints
  • Start from each interface and list every method it declares.
  • Check the header first: both interfaces are named, so the first condition holds.
  • Compare the list of methods with the class body; the method that is missing is the one you need.
MEDIUM

Write the header of a class Rectangle that extends Shape and implements both Strokeable and Fillable. Then state which methods its body must define.

Hints
  • The extends clause comes before the implements clause in the header.
  • Only one superclass is allowed, but the implements clause can list several interfaces separated by commas.
  • Every instance method declared by Strokeable and Fillable must appear in the body.

Key Takeaways

  • A Java interface is a reserved word that introduces instance method declarations with no implementations, and a class implements it by using implements in its header and defining every method the interface declares.
  • Interface methods are public and abstract, and interface variables are public static final, so those modifiers may be omitted while still applying.
  • A class meets an interface only when both conditions hold: the header names the interface with implements and the body defines every required method. Failing either one breaks the promise.
  • A class can extend one superclass and implement any number of interfaces, so an error can come from the extends clause, the implements clause, or a missing method in the body.