How do classes relate to each other? Associated Classes
Archive - Originally posted on "The Horse's Mouth" - 2012-02-12 15:49:29 - Graham Ellis
How do classes relate to each other? Associated Classes ... or ... define: Associated classes, parent classes, superclasses, subclasses, base classes, abstract classes, interfaces and mixins.
Associated classes are the odd ones out here. They're classes that are used within other classes.
Let me give you an example, from the Object Oriented PHP course I gave on Friday. We defined a class called visit, in which each instance contained an array of access objects (as well as some other data). One or more accesses make up a visit, and so every visit object must contain access objects, but that's not in the same way that properties and methods are inherited - a term which applies to all the other terms that I used above.
Let's look at all the other terms, and let's do so by example.
I define a class called pubtrans which contains information about a public transport offering. However, whilst public transport by one more or another is more or less the same, there are differences in the code logic needed. So I call my pubtrans class a parent class and I then provide extra (extended) logic to define a subclass for a train, and I also provide extra logic to define another subclass for a bus.
The parent class is sometimes referred to as the superclass, and you'll also find the term base class used to refer to the class on which another is based.
A class is referred to as an abstract class if you won't be creating (constructing) members directly. Taking our pubtrans as an example, that's likely to be an abstract class - every piece of public transport is some subtype of public transport be it a train, a bus, a ferry or a pogo stick. In an abstart class definition, you can usually include a requirement that each subclass must implement a particular method, thus ensuring that all the objects in this object tree are polymorphic.
An interface is a definition of a number of methods that must be defined in a class which implements it. It's rather like an abstract class which is so abstract that it contains no code at all. The advantage of an interface is that classes can implement multiple interfaces, then giving you something which approaches multiple inheritance in a language which only supports single inheritance such as Java.
Finally, a mixin is code / methods which are shared between a number of classes by being "mixed in" or added to them. They're currently used in Ruby and Python (of the languages that we train on) and will be present in PHP 5.4 onwards where they will be part of traits and offer a wider selection of operations such as aliasing and exclusion and will as mixingin.