Designing abstract types

Similar to many other objected-oriented programming languages, Julia supports a hierarchy of abstract types. Abstract types are typically used to model real-world data concepts; for example, an Animal could be an abstract type for a cat or dog, and a Vehicle can be an abstract type for a car, truck, or bus. Being able to group types together and give the group a single name allows Julia programmers to apply generic code that is common to those types.

Abstract types are often conveniently defined in a type hierarchy for a specific domain. We can describe the relationship between abstract types as parent–child, or more technically, an is-a-subtype-of relationship. The terminology for the parent type and child type is supertype and subtype respectively.

A unique feature of Julia's design, unlike the majority of other languages, is that abstract types are defined without any fields. For this reason, abstract types do not specify how data is actually stored in the memory. It may seem somewhat restrictive at first glance, but as we learn more about Julia, it will seem more natural when used in this design. As a result, abstract types are used solely to model behaviors for a set of objects rather than to specify how data is stored.

The Rectangle and Square object model is a classic example of how things can break down when an abstract type is allowed to define data fields. Suppose that we were able to define a Rectangle with width and height fields. A Square is a kind of Rectangle, so intuitively, we should be able to model Square as a subtype of Rectangle. But we soon get into trouble because a square does not need two fields to store the length of its sides; we should rather use a single side length field instead. Therefore, inheriting fields from supertypes makes no sense in this case. We will discuss this case with more details in Chapter 12, Inheritance and Variance.

In the following sections, we will work through an example of building an abstract type hierarchy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset