Inheritance & super

Every class has exactly one superclass (except ProtoObject, whose superclass is nil).

16.1 Single inheritance

Every class has exactly one superclass (except ProtoObject, whose superclass is nil). A subclass inherits all instance variables and methods and can add or override them.

Object << #Shape
    slots: { #name };
    package: 'Shapes'

Shape >> area
    ^ self subclassResponsibility         "abstract method"

Shape >> describe
    ^ self class name, ' with area ', self area printString

Shape << #Rect
    slots: { #width . #height };
    package: 'Shapes'

Rect class >> width: w height: h
    ^ self new setWidth: w height: h

Rect >> setWidth: w height: h
    width := w.
    height := h

Rect >> area
    ^ width * height

Rect << #Square
    slots: {};
    package: 'Shapes'

Square class >> side: s
    ^ self width: s height: s

Shape << #Circle
    slots: { #radius };
    package: 'Shapes'

Circle class >> radius: r
    ^ self new setRadius: r

Circle >> setRadius: r
    radius := r

Circle >> area
    ^ Float pi * radius squared
(Rect width: 3 height: 4) describe.    "→ 'Rect with area 12'"
(Square side: 5) describe.                  "→ 'Square with area 25'"
(Circle radius: 1) area.                    "→ 3.141592653589793"
Shape new area.                             "→ error: My subclass should have overridden #area"

16.2 super

super sends a message to self, but the lookup starts in the superclass of the class where the method is defined (not the receiver's class):

Always call super initialize at the start of initialize, and super setUp in tests.

Rect >> initialize
    super initialize.              "let Shape (and Object) initialize first"
    width := 0.
    height := 0

Square >> printOn: aStream
    super printOn: aStream.        "Rect's / Object's printOn:"
    aStream nextPutAll: ' (square)'

16.3 Abstract classes and template methods

Smalltalk has no abstract keyword. A class is abstract by convention if some methods send subclassResponsibility. The template method pattern is idiomatic: a superclass method (describe) calls hooks (area) that subclasses implement.

16.4 Inheritance vs composition

Inheritance in Smalltalk is for sharing implementation, and it is easy to abuse. Prefer composition (an object holding another) when there is no true "is-a" relationship. Since there are no interfaces, polymorphism needs no common superclass — any object that understands the messages will do (duck typing).

16.5 The hierarchy root

ProtoObject (minimal, for proxies) → Object (printing, comparing, copying, reflection, errors) → Magnitude, Collection, Boolean, UndefinedObject, Behavior, Exception, and thousands more. Explore with Object allSubclasses size, Integer withAllSuperclasses, Collection withAllSubclasses.