Task 5 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 — the interface as a type

Lesson

Polymorphism through a contract

An interface is a type: you can declare Shape s = new Circle(2);, build a Shape[] holding any implementers, and write methods that take a Shape parameter. Calling s.area() runs the actual object's version — the same dynamic dispatch as with a superclass, but the objects need share nothing except the contract.


Worked example

Shape[] shapes = { new Circle(1), new Rect(2, 3) };
for (int i = 0; i < shapes.length; i++) {
    System.out.println(shapes[i].name() + ": " + shapes[i].area());
}
// Circle: 3.14
// Rect: 6.0

One loop, one contract, two very different area formulas.


▶ Try it: run this — a Shape[] holds both classes and each answers with its own area.



Can you declare a variable of an interface type?


For Shape s = new Circle(2);, s.area() runs...


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){
    Shape[] arr = { new Sq(), new Tri() };
    for (int i = 0; i < arr.length; i++) System.out.println(arr[i].area());
}}

A method with a Shape parameter accepts...


True or false?