Ad hoc polymorphism 2026-10-24
Ad hoc polymorphism provides distinct implementations for selected types behind a common operation name. Method overloading is a common instance, where parameter signatures and static argument types determine the selected operation. It differs from a uniform type-parameterized definition and from dynamic dispatch on the receiver after an instance-method signature has been selected.
Double dispatch Created 2026-10-31 Updated 2026-11-05
Double dispatch selects behavior using the runtime types of two participating software objects, often by arranging two ordinary dynamic dispatch steps. The visitor pattern supplies a useful example.
Suppose
Shape has an overridable accept(Renderer) operation, and Renderer has overridable overloads visit(Circle) and visit(Rectangle). A Circle implementation of accept calls renderer.visit(this). Calling shape.accept(renderer) first selects Circle.accept using the shape's runtime type. Inside that method, this has the static type Circle because the method is defined in the Circle software class. Method overloading therefore chooses the visit(Circle) signature. The renderer's runtime type then selects the implementation of that signature.The result depends on both the concrete shape and concrete renderer. Ordinary method overloading alone would not inspect an argument's runtime type to choose the shape overload. The static type established in the first dispatched method is the bridge to the second dispatch.[ref]
Scala 2.11 expressions specification. Overloading Resolution, static argument typing; example uses ordinary overridable instance methods
Method overloading 2026-10-24
Several callable methods share one name but differ in parameter signatures. In ordinary Scala calls, the compiler chooses among applicable alternatives using the receiver and arguments' static types, preferring a uniquely most-specific applicable alternative. Overloading is therefore a different step from method overriding and receiver-based dynamic dispatch.
Method overriding 2026-10-24
A subclass or composed trait supplies an implementation of an inherited method signature. Ordinary instance calls use dynamic dispatch to choose the effective implementation for the receiver, after any overload selection. In Scala, overriding a concrete inherited member requires the
override modifier; a qualified super invocation selects the corresponding inherited implementation. Object method Created 2026-10-25 Updated 2026-10-31
An operation invoked on a software object that can read or modify that receiver's state. Its contract specifies accepted inputs and effects. Dynamic dispatch can select an overriding implementation according to the receiver's concrete software class; method overloading instead selects among different signatures using static type information.
An ordinary call such as the unqualified HenceThese arrows describe the method bodies entered in order, not the class inheritance relation. An inherited method continues to use the dynamic receiver for ordinary calls; it does not acquire the defining software class as a new receiver.
f inside A.g uses dynamic dispatch on the receiver. Thus c.g enters A.g, but its call to f reaches C.f. In contrast, B.h explicitly invokes super.f, which continues after B and therefore reaches A.f. Finally A.k dynamically dispatches its call to h, reaching B.h again. The output isg in A, f in C
h in B, f in A
k in A, h in B, f in AMethod overloading chooses a signature using the static types available at the call site. The receiver
m has static type M, whose visible overloads accept X and Y; the Z overload introduced only in N is not a candidate.For Equivalently,The runtime type of every argument is
m.f(x), the argument's static type is X, so the chosen signature is f(X). N does not override it, and the inherited M body runs. For m.f(y), the chosen signature is f(Y), and dynamic dispatch on the receiver chooses N's override. For m.f(z), both visible signatures apply, but f(Y) is more specific than f(X). Dynamic dispatch again chooses N.f(Y). Thusf with X at M
f with Y at N
f with Y at NZ, but ordinary single-receiver dynamic dispatch does not redo method overloading using that runtime type. This is overload selection followed by dynamic dispatch.Use double dispatch. Each original overload first sends a dynamically dispatched message to its argument. The argument's selected body then calls an overloaded receiver method with All three
this, whose static type inside that body is the desired argument software class.class X {
def sendTo(m: M): String = m.receive(this)
}
class Y extends X {
override def sendTo(m: M): String = m.receive(this)
}
class Z extends Y {
override def sendTo(m: M): String = m.receive(this)
}
class M {
def f(x: X): String = x.sendTo(this)
def f(x: Y): String = x.sendTo(this)
def receive(x: X): String = "f with X at M"
def receive(x: Y): String = "f with Y at M"
def receive(x: Z): String = "f with Z at M"
}
class N extends M {
override def f(x: Y): String = x.sendTo(this)
def f(x: Z): String = x.sendTo(this)
override def receive(x: X): String = "f with X at N"
override def receive(x: Y): String = "f with Y at N"
override def receive(x: Z): String = "f with Z at N"
}receive overloads must be declared in M, because sendTo receives a parameter with static type M. Declaring the Z version only in N would repeat the original problem.Whatever original The result depends on both runtime types:For the stated
f signature is selected, it invokes sendTo on the actual argument. For a Z object, dynamic dispatch enters Z.sendTo; inside that body, this has static type Z, so method overloading selects receive(Z). The final call dynamically dispatches on the actual m, giving N.receive(Z) when m refers to N. Hencef with Z at N
f with Z at N
f with Z at NX, Y, Z hierarchy, the same construction reports each argument software class correctly for either receiver software class. Further subclasses would need their own dispatch protocol to distinguish additional runtime types.Apply overload selection followed by dynamic dispatch: the receiver's static type determines visible signatures, and argument static types choose the overload. The receiver's runtime type then selects its override. A
super call starts at the inherited implementation instead of redispatching to the override just entered.For
c.f1(y), the Y overload is visible on C, so its body in C runs. For a.f2(x), the X signature is selected and its override in C calls C.f1(X). For a.f2(y), the Y signature is selected; its body in C calls super.f1(y). The superclass B has only f1(X), so that call uses B.f1(X).For
b.f3(y), the static type B exposes only f3(X). Its override in C calls super.f2(x), entering B.f2(X). The unqualified f1(x) inside that body still uses dynamic dispatch on the original C instance, so it calls C.f1(X).Finally
c.f4(x) invokes the companion object C, which is a separate receiver extending B. Its f3(X) calls inherited B.f2(X), whose f1 call dispatches to ObjC.f1(X).[ref]Imperative Programming examination paper by the University of Oxford (2014). p. 10, Question 6(a), method bodies and calls
Apply overload selection followed by dynamic dispatch: method overloading chooses a signature from the receiver's static type and argument static types, then dynamic dispatch chooses an override of that signature using the receiver's runtime type. A
super call selects the inherited implementation; a call on the companion object B uses that object's own methods.[ref]Scala 2.11 expressions specification. Static overload resolution; this and super
The output, in order, isFor
f(x:X) in B
f(y:Y) in A
f(x:X) in A, g(x:X) in B
f(x:X) in ObjB, g(y:Y) in ObjB, h(y:Y) in B, h(z:Z) in C
f(y:Y) in C, m(a:A) in Y, k(x:X) in Ca.f(x), the argument's static type is X, selecting f(X); the receiver's runtime type B selects B.f(X). For a.f(z), the receiver's static type A exposes only f(X) and f(Y). The Z argument fits both, and f(Y) is more specific. B does not override that signature, so A.f(Y) runs. The additional overload B.f(Z) is invisible through a.For
c.g(z), the inherited instance B.g(X) calls super.f(x), which is A.f(X). For c.h(z), method overloading selects C.h(Z). Its super.h(z) calls B.h(Y), where the local parameter has static type Y. Consequently B.g(y) selects g(Y) on the companion object, whose only f signature is f(X).Finally,
c.k(x) calls x.m(this). The receiver x has runtime type Y, so dynamic dispatch enters Y.m(A). Inside that method, this has static type Y, selecting a.f(Y); the actual argument object is c, so dynamic dispatch reaches C.f(Y). ThereforeThe five printed lines, including the comma and space after every fragment, are:Scala dynamic dispatch uses the receiver's runtime software class, even though
f1 in C,
f1 in C, f2 in B,
f1 in C, f2 in A, f3 in B,
f1 in A, f2 in A, f3 in ObjB, f4 in B,
f1 in ObjC, f2 in A, f3 in B, f4 in ObjC, f5 in C, a has the static type A. Thus a.f1 uses C.f1, and a.f2 uses B.f2 whose unqualified f1 still dispatches on the new C receiver.For
a.f3, B.f3 explicitly selects super.f2, which is A.f2. Inside A.f2, the unqualified call to f1 still dispatches to C.f1; super does not replace the receiver. For a.f4, B.f3 in the body of class B means a call on the singleton object B, not on this. That object's f3 calls A.f2, which calls A.f1.Finally
a.f5 calls C.f4 on the singleton object C. That object extends class B, overrides f1 and f4, and inherits class B's f3. Its f4 calls this inherited f3; that selects A.f2, whose f1 dispatches to the object's own override. These distinctions follow member selection and super semantics.[ref]Scala 2.11 expressions specification. This and Super; Designators, member selection
The output is
YY, with no newline. The variable a has static type A, although its runtime type is B. Both c.m(a) and d.m(a) therefore select the signature m(A) at compile time. The m(B) alternative is not applicable to an argument whose static type is merely A.Both receivers refer to the same
D object. Dynamic dispatch then invokes D's override of the already selected m(A) signature, printing Y twice. The static type C of c changes the visible member set, but both signatures are visible through either receiver in this example. Overload selection followed by dynamic dispatch does not select an overload from the argument's runtime type.Two mechanisms are subtype polymorphism and parametric polymorphism.
With subtype polymorphism, a trait or abstract class declares an operation and concrete subclasses implement or override it. A
Player reference holding a House object invokes House.play through dynamic dispatch. The client is written against the common contract.With parametric polymorphism, a software class or generic method has a type parameter, such as
List[T] or def identity[T](x: T): T = x. The same definition works for many supplied type arguments, with static relationships between input and output types. Method overloading is another mechanism, usually called ad hoc polymorphism: alternatives share a name but are selected from their parameter signatures at compile time.Each The Scala assignment
play call should make at most one hit and return true exactly when it did so; the supplied while loop invokes it again to decide whether another hit is needed. Add these accessors inside Player:def cards: List[Int] = _cards
def cards_=(cs: List[Int]): Unit = { _cards = cs }
def visibleValue: Int = _visibleValue
def visibleValue_=(v: Int): Unit = { _visibleValue = v }temp.cards = cs calls the setter, and visibleValue += cards.head uses the getter followed by the setter. The list getter exposes an immutable list value; updating the player's field still goes through the setter. The supplied initialization and hit maintain the hidden card at the last list position and visibleValue == cards.init.sum for each nonempty dealt hand.The concrete software classes implement the supplied strategies literally:
class Regular extends Player {
def play(visibleCards: List[Int]): Boolean = {
require(visibleCards.length == 1)
val total = value
if (total < 21 && total <= 21 - visibleCards.head) {
hit
true
} else false
}
}
class Optimistic extends Player {
def play(visibleCards: List[Int]): Boolean = {
if (value != 21) {
hit
true
} else false
}
}
class House extends Player {
def play(visibleCards: List[Int]): Boolean = {
val total = value
if (total < 21 && visibleCards.forall(v => total <= 21 - v)) {
hit
true
} else false
}
}House receives all other players' final visible totals, whereas a non-house player receives the singleton containing the house's first visible card. The universal test implements “for each other player,” including the vacuously true case of no other players. Subtype polymorphism gives the common player list a Player interface, and dynamic dispatch chooses the appropriate play implementation.These are the literal missing methods, but the printed specification does not guarantee a terminating game. An optimistic player with total who draws reaches ; every further positive card keeps the total above , so
value != 21 remains true. The claim that only finitely many further cards are requested is therefore inconsistent with the optimistic strategy on such executions, in the intended arithmetic model without overflow. If the intended rule is “stop on reaching or exceeding 21,” the necessary correction is to replace its test by value < 21; that changes the printed strategy and is not silently made here.There is a second printed mismatch:
nextInt(10) yields , so 1 + nextInt(10) yields , not . Preserve the supplied hit when filling its missing pieces; generating every value from through would require an explicit change to nextInt(11) in both dealing and hitting.[ref]https://www.scala-lang.org/api/2.11.12/scala/util/Random.html#nextInt(n:Int):Int. Scala 2.11.12 Random.nextInt, upper bound is exclusive
No winner-computation code is requested; the supplied loop only deals and requests cards.The output is
YXWX, without a newline. Apply overload selection followed by dynamic dispatch separately to each call:Although
a actually refers to a B, that runtime type does not select another overload. Dynamic dispatch chooses the implementation of the already selected signature on the receiver.Each implementation first evaluates There is a trailing space before each newline. The third and fourth lines are identical: the declared type
super.meth and then appends its own name. Consequently the contributions appear in reverse order of the defining traits in the Scala trait linearization. The four printed lines areE I L N H Y
E I D L N H Y
E I D L T H S Y O N
E I D L T H S Y O N D of o4 permits the call but does not change the actual A object's dynamic dispatch or its super chain. Within N, for example, super.meth in an A follows the next implementation in A's full linearization rather than simply using L as its isolated textual parent.Class inheritance defines a software class by extending another software class, inheriting its available operations and optionally adding members or providing method overriding. In languages supporting it, traits and mixins can contribute reusable behavior as well.
Use inheritance for a sound specialization whose instances can satisfy the superclass's contract wherever its instances are expected. For example, every specific gate in part (d) is usable through the common gate object interface. Subtyping supports this substitution and dynamic dispatch selects the specialized calculation. Merely noticing shared code does not establish the required behavioral relationship; object composition is often better for a replaceable component or policy that an object contains. A subclass must preserve the superclass's promised behavior, rather than just sharing its field names.
The two writable inputs and Boolean query belong to an abstract class; each concrete logic gate overrides just that query:All three subclasses satisfy the same object interface, so the
abstract class Gate {
var inp1: Boolean = false
var inp2: Boolean = false
def evalGate: Boolean
}
class OrG extends Gate {
override def evalGate: Boolean = inp1 || inp2
}
class AndG extends Gate {
override def evalGate: Boolean = inp1 && inp2
}
class XorG extends Gate {
override def evalGate: Boolean = inp1 ^ inp2
}Gate declarations in the supplied simulator still allow access to inputs and invoke the correct Boolean function through dynamic dispatch. Boolean ^ is exclusive or; || is Boolean disjunction and && is Boolean conjunction.The program first sets both inputs of Those are the two output lines. This is a simulation of combinational logic in an order where each gate's inputs have already been calculated; the Boolean assignments copy values rather than create live wire connections.
y, so . It sets . Therefore and , givingx: true
w: falseThe three printed lines are:
g in A, f in C
h in B, f in A
k in A, h in B, f in AThe inherited
A.g makes an ordinary virtual call to f, selecting C.f by dynamic dispatch. B.h instead invokes super.f, which selects the next implementation after B, namely A.f. Finally, A.k makes an ordinary virtual call to h, selecting B.h and its already determined result. A super call is not redirected back to the most-derived override.The printed lines are:
f with X at M
f with Y at N
f with Y at NMethod overloading first uses static types. The receiver
m has static type M, whose available signatures are f(X) and f(Y). Argument x selects f(X); y selects f(Y); and z, statically Z, also selects f(Y) because that is the most specific available applicable signature. N.f(Z) is not available through the static receiver type.Only after a signature is selected does dynamic dispatch choose an override for the runtime receiver
N. That class overrides f(Y) but not f(X), explaining all three lines. The shared argument object's runtime class does not trigger a second overload-resolution pass.