8.15.0.4

4.8 Private Implementation🔗ℹ

Although private and protected are normally used on methods and fields, an implements clause also can be modified by private or protected. A private or protected implementation of an interface avoids exposing the implementation of the interface’s method to untrusted callers. The implementation of the interface is still accessible via the interface’s internal name, which might be made available only to trusted contexts.

For example, suppose that we’d like to customize printing by implementing the Printable interface, but we don’t want a public print method. Printing and string conversion access customization methods using an internal name for Printable, so privately implementing Printable will achieve the goal.

To privately implement an interface, use private implements, and override the interfaces methods with private methods.

class Posn(x, y):

  private implements Printable

  private override describe(mode, recur):

    PrintDesc.list("⟨⟨⟨", [recur(x), recur(y)], "⟩⟩⟩")

> Posn(1, 2)

⟨⟨⟨1, 2⟩⟩⟩

> Posn(1, 2).describe(#'expr, Function.pass)

describe: no such field or method

  in value: ⟨⟨⟨1, 2⟩⟩⟩

A protected implementation of an interface is similar to a private one, but the implemented methods are visible in subclasses, and the methods can be overridden in subclasses.