Home > Articles

Classes and Objects

This chapter is from the book

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.

03fig01.jpg

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020