Skip to main content

What is a Subtype

Posted by mortazavi on January 2, 2006 at 2:38 PM PST

One thing that attracted me to Java was its type system. This was an area where C++ always appeared to be too confusing. (A graft can be better than the original tree in gardening but this is not always the case in software engineering and programming languages.)

Before Java first came out, I had had much more than the essentials and the usual grounding in type theory that one expects in computer science. (I was certainly not preparing for Java when I sat through several years of graduate courses in logic and set theory at the math department, some courses in philosophy of math and language in the philosophy department and a graduate languages course in the computer science department at Berkeley.)

My first impression of Java was that it made OO programing quite simple and natural.

In OO, the most fundamental concept is that of subtyping.

What's a subtype?

Well, if Tb is a subtype of Ta, then any value vb of type Tb can be substituted where a value of type Ta is expected.

This is really quite fundamental but many just miss its power and get tangled in designing their systems based on interfaces, lots of classes that implement those interfaces and all the compositions that they can muster. Of course, there is great value in that sort of approach but to pursue it just in order to avoid subtyping seems a bit extreme.

In Java, subtyping can be done either through sub-classing, sub-interfacing. When it comes to the type relationship of a class which subtypes an interface, we rely on the class to implement a subtype (or a sub-interface) of that interface.

And of course, all types are subtypes of themselves!

Subtyping is a kind of ordered system and as model theory tells us, such a system is complete, i.e. we can reason about it effectively and reach all the valid conclusions there is and, what is more, we are guaranteed to do so within some bound.

By the way, a type system is essentially a safety mechanism.

Many believe a strongly typed system reduces "freedom" (this is true in the sense that some constraints are put in place that are not there in a loosely typed language) but this interpretation of freedom depends on how one interprets freedom. As James Gosling has noted in a recent entry, safety itself can be viewed to provide the most fundamental freedom.