Java course Lesson 6 of 6

Java from zero: one method is enough to call

An interface is the method list a function needs. Labeller asks for label. Item has label. show prints latte $4.50.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

show needs a label. It does not need to know that the price is cents or that the class is named Item. An interface lists the methods the caller uses. A class opts in with implements and provides those methods.

The caller names the method, not the class#

An interface is a list of methods. Labeller lists label(). Item declares that it implements the list, and the compiler checks that the method is really there, with the same name, parameters, and return type. show accepts any Labeller. Inside show the only thing you can do with the argument is call label. The fields stay on Item. A second class with the same method can be passed in without editing show.

show needs label, and Item has it
  1. Itemlabel()latte $4.50
  2. unrelatedno labeldoes not compile
public class Main {
    interface Labeller {
        String label();
    }

    static class Item implements Labeller {
        String name;
        int cents;

        Item(String name, int cents) { this.name = name; this.cents = cents; }

        public String label() { return String.format("%s $%d.%02d", name, cents / 100, cents % 100); }
    }

    static void show(Labeller item) {
        System.out.println(item.label());
    }

    public static void main(String[] args) {
        show(new Item("latte", 450));
    }
}
latte $4.50

implements is the promise#

Labeller has one method, label(). Item implements Labeller says Item provides it. The method is public because an interface method is public. show takes a Labeller and calls label. main passes an Item. The fields never appear in show.

A second class with its own label method can be passed to the same show. That is the useful part of the interface. The caller depends on the behavior, and each class owns its fields.

Keep the list to the methods you call#

If Labeller also demanded the name and the cents, every caller would know the fields, and the interface would be a second copy of Item. List label, because show calls label. A class can implement more than one short interface. A long interface that no class can satisfy is a design you will fight later.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.