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.4 Choosing — combining both

Lesson

Inheritance for code, interfaces for capability

Real designs use both. A class extends an abstract class to inherit shared state and code, and implements interfaces to advertise capabilities. Then an interface-typed array can hold objects from completely unrelated class hierarchies — something a superclass array could never do.


Worked example

class Rect extends Shape implements Printable { ... }   // a shape, and printable
class Tag implements Printable, Sized { ... }           // not a shape, still printable

Printable[] items = { new Rect(2, 3), new Tag("hi") };
for (int i = 0; i < items.length; i++) {
    System.out.println(items[i].label());
}
// [Rect]
// <hi>

Rect and Tag share no superclass — only the Printable contract — yet one loop handles both.


▶ Try it: run this — a Printable[] mixes a Shape subclass with a totally unrelated class.



A Printable[] can hold...


Why can an interface array mix unrelated classes, but a superclass array cannot?


Type exactly what this program prints.

interface Printable { String label(); }
class A implements Printable { public String label(){ return "A"; } }
class B implements Printable { public String label(){ return "B"; } }
public class Main { public static void main(String[] x){
    Printable[] arr = { new A(), new B() };
    for (int i = 0; i < arr.length; i++) System.out.println(arr[i].label());
}}

Match each need to the better tool.


True or false?