Home

upcasts

An upcast is a cast or conversion of a value to a supertype in a type hierarchy, commonly described as a widening conversion. In object-oriented languages that support subtyping, upcasting often involves treating an instance of a subclass as an instance of its superclass or an implemented interface. The operation is usually implicit and safe, because the runtime type remains the same and all behavior defined by the supertype is preserved.

In practice, upcasting is used to enable polymorphism. For example in Java: Dog d = new Dog(); Animal

Downcasting is the reverse and may require explicit casts; it can fail at runtime if the underlying

In type systems, upcasting corresponds to subtyping; it is fundamental to polymorphism, interfaces, and virtual method

a
=
d;
The
variable
a
uses
the
Animal
type,
so
only
methods
declared
in
Animal
are
accessible,
though
the
object
is
still
a
Dog
and
may
override
Animal
methods.
object
is
not
actually
of
the
target
subtype.
Upcasting
does
not
typically
incur
runtime
checks,
although
some
languages
may
insert
checks
for
certain
interfaces
or
generic
types.
dispatch.
When
using
generics
or
type
erasure,
upcasting
behavior
can
be
constrained
by
the
language's
rules.
Some
languages
also
permit
upcasting
through
interface
references,
or
to
a
base
class
such
as
Object
in
Java.