8.12

4.1 Subclasses🔗ℹ

In a class body, extends followed by the name of an existing class. Instances of the new class, the subclass, will also count as instances of the existing class, the superclass. Since that creates obligations on the superclass, however, a class is final by default, which means that it does not permit subclasses.

class Posn(x, y)

class Posn3D(z):

  extends Posn

class: superclass is final and cannot be extended

To allow subclasses, add a nonfinal clause in a class:

class Posn(x, y):

  nonfinal

class Posn3D(z):

  extends Posn

When a subclass is created, superclass fields are implicitly included before new fields in the subclass’s constructor:

> def p = Posn3D(1, 2, 3)

> p

Posn3D(1, 2, 3)

> p.y

2

> p is_a Posn

#true

> p is_a Posn3D

#true

The interface definition form is similar to class, but without fields. A class form can declare that the class implements an interface through an implements clause. When a class implements an interface, then instances of the class satify the interface annotation, similar to the way that a subclass instances satifies the superclass annotation. A class can have at most one superclass. but it can implement any number of interfaces. An interface is never final, so no nonfinal is needed in an interface.

interface Shape

interface Dance

class Square(side):

  implements:

    Shape

    Dance

> def s = Square(10)

> s is_a Shape

#true

> s is_a Dance

#true