Task 3 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 — many classes, one contract

Lesson

Unrelated classes, same promise

Many classes can implement the same interface, each in its own way. They need not be related by inheritance at all — a Circle and a Rect share no superclass, yet both are Shapes because both fulfill the contract. This is the key difference from extends: an interface groups classes by what they can do, not by what they are.


Worked example

class Circle implements Shape {
    public double area() { return 3.14 * r * r; }
    public String name() { return "Circle"; }
}
class Rect implements Shape {
    public double area() { return w * h; }   // different formula
    public String name() { return "Rect"; }
}

Both classes satisfy Shape, but each computes area() its own way.


▶ Try it: run this — two unrelated classes, both honoring the same contract.



Can two classes with no common superclass implement the same interface?


Two classes implementing area() can...


Type exactly what this program prints.

interface Shape { double area(); }
class Sq implements Shape { public double area(){ return 4.0; } }
class Tri implements Shape { public double area(){ return 6.0; } }
public class Main { public static void main(String[] a){
    System.out.println(new Sq().area());
    System.out.println(new Tri().area());
}}

Match each keyword to its meaning.


True or false?