Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

8.1 Interfaces — a contract of methods

Lesson

Promising what a class can do

An interface is a contract: a list of method signatures with no bodies. A class that says implements Shape promises to provide a body for every method in the interface. Unlike a superclass, an interface holds no fields and no code — it only states what must be done, never how.


Worked example

interface Shape {
    double area();    // no body — just the signature
    String name();
}

class Circle implements Shape {
    private double r;
    public Circle(double r) { this.r = r; }
    public double area() { return 3.14 * r * r; }   // must provide
    public String name() { return "Circle"; }        // must provide
}

If Circle left out either method, it would not compile — the contract is not fulfilled.


▶ Try it: run this — Circle implements both interface methods, so both can be called.



An interface contains...


class Circle implements Shape means Circle must...


Type exactly what this program prints.

interface Shape { String name(); }
class Circle implements Shape { public String name(){ return "Circle"; } }
public class Main { public static void main(String[] a){
    System.out.println(new Circle().name());
}}

If a class implements an interface but omits one method, then...


True or false?