Understanding Classes and Objects in REALbasic
- The Class Hierarchy
- Creating a New Class
- Declaration and Instantiation
- Constructors and Destructors
- Garbage Collection
- Inheritance
- Object Operators
- Adding and Overriding Methods
- Calling the Overridden Method
- Overloading
- Casting
- Oddities
- Encapsulation
- Access Scope: Public, Private, Protected
- Setting Properties with Methods
- Default and Optional Parameters
- Declaring Variables Static and Const
- Revisiting the StringParser Module
- Example: Creating a Properties Class
- Data-Oriented Classes and Visual Basic Data Types
- Advanced Techniques
The Class Hierarchy
A former colleague used to say that he had "developed this new technology" whenever somebody in his department wrote a few lines of VBScript for the website. He is not the first person to use overly fanciful language to describe programming exploits. It happens all the time. Object-oriented programming is a particularly jargon-rich field of study, laden with ill-formed metaphors and polysyllabic titles. There was a time when object-oriented programming (OOP) advocates would say that OOP was easier to learn than more traditional styles of programming. I don't know if that is true; I suppose the fact that I have deferred the discussion of the object-oriented features until the third chapter of this book is some indication of how I feel about this subject.
One of the biggest challenges facing a novice programmer is the reality that knowing how to program and knowing how to program well are two different things. Learning a programming language is cut and dried (albeit a bit tedious at times). Learn the syntax and you've learned the language. It's very much a science. Doing it well, however, is much more like an art—something that is learned over time and something that you get a "feel for" that is often difficult to explain simply and clearly. In this chapter, I hope to provide an overview of object-oriented concepts and how they are implemented in REALbasic, and give some insight into strategies for executing your object-oriented programming effectively.
Cities are full of buildings, and each building has a particular street address, which can tell you how to find the building if you are looking for it. Computers have addresses, too, but instead of identifying buildings, these addresses point to locations in memory. Variables, properties, functions, and subroutines all reside at a particular address, too, when they are being used by your program.
When you declare a variable, you assign a type to the variable. To date, most of the variables in the examples have been one of REALbasic's intrinsic data types. When a variable is used in this way—pointing to an intrinsic data type—it's said to be a scalar variable. The variable represents the value that's stored at a particular location in memory.
Variables can also be used to represent objects. When they do, they aren't scalar variables anymore because an object doesn't represent a value in the way that an intrinsic data type does. The variable is said to be a reference to the object; it points to the location in memory where this object resides. An object is a collection of different things and can be made up of properties and various methods. In this respect it is like a module, but it differs from a module in some very important ways.
Suppose we have an object with two different properties, one called FirstName and the other called SecondName, both of which are Strings. Let's also say that we have a variable called Person that points to this object. Referring to the object itself doesn't refer to any particular value, because the object has multiple properties. This means that to access a particular property of an object, you need to refer to the object itself, plus the property. You do this using the familiar dot notation, like so:
Person.FirstName
This should look familiar because it's the way you refer to protected properties and methods of modules. The biggest difference is that you always have to refer to an object's members this way, even if the property is public.
Now knowing that an object is a collection of values is only a small part of the story. What makes objects powerful is that they are members of classes. To create an object, you must first create a class.
To explain what classes are conceptually, I'll return to the building and street address analogy. If you pull up to any address, you'll find a building. If you were to come visit me, you could drive until you reached my address; pull in the driveway and you'd be at my house. My house is a building, but it's a different kind of building than you might find down the street a bit where there is a grocery store and a gas station. Furthermore, my house is just one example of a particular type of house. Houses come in all styles—some are ranches and others are Cape Cod or Tudor styles.
Whether you are talking about houses or grocery stores or gas stations, every building has some things in common—a roof and some walls, for example. I live in a single-family residential neighborhood, so every building on my street is a house. The fact that it is a house means that in addition to a roof and some walls (which all buildings have), it also has at least one bedroom, a bathroom, and a kitchen, because buildings that happen to be houses all have those features.
If I were to try to systemize my understanding of buildings, I might start by classifying buildings into the different types of buildings and showing how they are related. A good way to do this is by organizing buildings into a conceptual hierarchy, like the one outlined in Figure 3.1.
Figure 3.1 Different styles of houses can be organized in a hierarchy.
Every node on this tree represents a type of building or, to use object-oriented terminology, a class of building. At the top of the hierarchy is the base class, and it has two subclasses—residential and commercial. You can say that the building class is the superclass of the residential and commercial classes. In addition to the super/subclass terminology, you also hear people refer informally to them as parent classes and child classes.
One way that we make these classifications is based on physical attributes of the buildings themselves—things such as walls and doors. At the same time, we also consider the kind of activity that takes place in them.
This isn't the only way to classify buildings. You might come up with a different hierarchy that's equally valid. For example, you might decide that the most important differentiating factor isn't whether a building is residential or commercial, but how many stories the building has. You might start off with building, and then branch to one-story buildings and multistory buildings, and go on from there.
Even the buildings themselves can be subdivided into smaller units. A house doesn't just sit empty. People live in them and do things. The house is organized into rooms and these rooms are designed for certain activities. In one room you cook, in another you watch TV, and so on. Some rooms have storage areas, such as closets and cupboards, and others have tools, such as stoves and refrigerators and washing machines.
The hierarchy shows classes of buildings, not particular buildings themselves. A description of a house is not any particular house; it's a description of what houses that are members of that class have in common. One way to think of classes is to think of them as a blueprint, or a design, for a building. You can build many houses using the same blueprint. If a class is analogous to a blueprint, an object is analogous to a particular house.
After you've driven to my house and you're standing in the driveway looking at it, you are looking at one particular instance of a house. There are other houses in the neighborhood that were built from the same plan, but they are filled with different people, doing different things.
One thing you may have noticed when I classified buildings and organized them into a hierarchy is that I didn't list all the features of each class of building at each level. At the top level, I said buildings have roofs, walls, and doors. At the second level of the hierarchy, I didn't repeat that they have roofs, walls, and doors because I wrote down only what was new and unique about the next group. The assumption is that the subclass has all the attributes of the superclass, plus some additional attributes that differentiate it from the superclass. To put it another way, the subclass inherits the features of the superclass.
Inheritance is a big deal, and it's just about the coolest part of object-oriented programming. In practical terms, this means that when you write your program, you organize your code into classes. The advantage of this kind of inheritance from a programmer's perspective is that it keeps you from having to rewrite as much code. The subclass inherits all the functionality of the superclass, so that means you don't have to write new methods in the subclass that replicate the basic functionality of the parent.
And this leads to the challenging part. It's up to you to decide how to organize your classes. You can do it any way you like, but you need to do it in a way that makes sense and in a way that maximizes code reuse (from inheritance). Knowing how to write the code that creates a class is only half the battle. Knowing what goes into the class is the hard part. There is no single solution; the answer is really dependent on the kind of program you are going to write. You have to figure out what makes the most sense for your application.
Again, I'll return to the house analogy. Inside my house, the downstairs is divided into six rooms: a living room, a dining room, a kitchen, a bedroom, a bathroom, and a laundry room. In the kitchen are cupboards. Some are full of food and others are filled with plates and dishes. There is a refrigerator, stove, and so on. Likewise, in the laundry room you'll find laundry detergent, and then there is the usual stuff that goes into a living and a dining room.
This makes sense—the reason I put the laundry detergent in the laundry room with the washing machine is because it's convenient and makes sense. Likewise, I put my clothes in my closet so that I can find them in the morning and get dressed.
That's exactly how object-oriented programming works, too. A class in object-oriented programming groups together information and instructions for what to do with the information. It's a place to store information of a particular kind, and a set of instructions for what to do with it. When you are creating classes, you have to decide what kind of information makes sense to be associated with what kind of tasks.
Although objects are capable of having properties, constants, and methods, they are not required to have them. A chair, for example, is an object. By definition, a chair doesn't do anything. It can only have things done to it. It can be sat upon. It can be held in place by gravity. It can be broken and it can be painted red. But it can't scoot itself up to the table, or teeter precariously on two legs, unless a child is in the chair to do the teetering. An object from the programming perspective can be dull and boring like a chair. It can be a thing, a set of values, or, as they are called in REALbasic and other languages, it can have properties.
An object can be nothing more than a set of properties. In this respect, an object is very similar to a struct or User Defined Type familiar to Visual Basic programmers. It can also have methods, constants, events, and menu handlers, all of which will be covered in due time.
There are some basic concepts to discuss first, and the best way to discuss them is to illustrate them by creating a class or two and looking at what we are doing. In particular, I want to discuss some important OOP concepts: inheritance, encapsulation, and polymorphism. Much like calling a new script a new technology, these words create a certain mysterious aura that make everything sound much more complicated than it is. Hopefully, after you've read this chapter you'll have enough mastery of REALbasic's flavor of object-oriented programming to use it with confidence.