Let’s start with the simple question “What is an object?” The easiest answer is that an object is simply an aggregation of values. Here I don’t mean to use aggregation as a highly technical term. In this context it means no more and no less than “a bunch of.” So, the simple answer is that an object is just a bunch of values.
Values associated with an object can just work like values associated with a variable, in which case the value is called a property of the object. For example, if you have a rectangle object, it might have height and width properties, each having numeric values.
The dot operator, which is a period (.), is used to show the relationship between an object and its values. You’ve already seen quite a few examples involving the dot operator in the earlier chapters of this book, so you probably are pretty familiar with it by now.
For example, taking the rectangle.width property I mentioned a moment ago, this statement:
rectangle.width = 75;
assigns the value 75 to the width property of the rectangle object. The following statement:
var theNum = rectangle.height;
retrieves the value stored in the rectangle.height property and assigns it to the variable theNum.
This simple example shows you one of the advantages of working with objects: An object serves to group conceptually related values. Conceptual grouping such as this leads to the ability to create modular programs that are easy to understand, debug, and maintain.
|Advanced Note|| |
So far, we’ve been looking at objects from the viewpoint of the programmer who is an object user rather than from the viewpoint of the programmer who is an object creator. From the viewpoint of an object creator, there’s a technical difference between object fields, which are implemented exactly as you would implement a variable storing a value, and object properties, which are implemented using special property functions. To expand on this a little, an object field is simply a variable associated with an object, whereas an object property consists of a variable and special access functions used to read and write the variable.
The values associated with an object can also be functions. (For more about functions, see Chapter 5, “ Understanding Functions.”) A function associated with an object is called a method. Another way of putting this is to say that object methods are implemented using functions.
The methods of an object do something. There’s no absolute technical requirement that the something the method does be related to the object or use the property values related to the object. But most of the time, methods perform tasks that you’d expect to be related to an object.
Because methods do something, it’s good practice to name them to show what they do. This means that a method should be named using a grammatical verb and a grammatical object that show the action and what’s acted on. For example, taking the rectangle object, a good name for a method that calculates the area of the rectangle, using the height and width properties of the rectangle object, might be calcArea.
Collectively, the fields, properties, methods, and events of an object are called the object’s members.
Let’s sit back for a moment and consider the concept of a class and how it relates to objects. It’s likely you’ve heard the term class before (and I don’t mean something you attend, snooze through, and try for a good grade!). A class is a blueprint for an object. It’s a central concept in object-oriented programming.
There are a number of metaphors used to say the same thing, but it may be helpful to repeat some of them. A class is a blueprint, and the object is a building built from it. A class is a cookie cutter, and the object is the cookie. Yum!
When all is said and done, this boils down to the notion that you can roll out many objects based on one class. The objects have in common prebuilt characteristics, such as the properties and methods supplied by the class (the blueprint). One advantage of this is that you don’t need to recreate these properties and methods each time—because they’re specified in the blueprint (the class).
An object that’s based on a class is called an instance of the class. When one creates a new object, one is said to instantiate the object.
When you create a new instance of an object, as you might suspect, you’re actually calling a function. This kind of specialized function, whose job is to create and initialize new object instances, is called a constructor. (Perhaps this goes along with the blueprint metaphor: You need a constructor to actually build the house.)
At this point, the picture you should have in your head is of a number of objects based on a class. These objects all have the same properties and methods although of course the value of these properties and the action of these methods are different for the different instances of the objects.
Now let’s run through some other concepts related to OO programming.
There’s a significant distinction to be made between instance members of a class and shared members of the class. Instance members are associated with an object created from a class. To use an instance member, you must first instantiate an object. The values of the members of different instantiated objects (even though they’re based on the same class) will differ.
It’s likely that the single most important concept in OO is inheritance. This is a concept that’s intuitively easy to grasp. When one class inherits from another class, it “gets” all the members of the class from which it inherits. In other words, all the code associated with the original class is now part of the inheriting class.
It’s easy to see why inheritance is powerful. Once you’ve created your original class, you can, in a single statement, give all its functionality to the classes that inherit from it, which may then extend this functionality with their own capabilities.
You should also know some vocabulary that’s sometimes used with inheritance. When a class inherits from another class, the inheriting class is said to be a subclass of the class from which it inherits. The original class is said to be a superclass of its subclass. Subclass is sometimes also used as a verb, as in “I’ve subclassed the Widget class by creating a RotaryWidget class that inherits from it.” (In this example, the Widget class is a superclass of the RotaryWidget class.)
In everyday life, you deal with a great many objects (for example, this book). Sometimes your things are messy, which isn’t fun and makes it hard to find things. Disorganized code is a huge problem, and organizing your programs using objects and object hierarchies helps to produce “neatnik” programs that have great clarity.
A class interface is a kind of contract for classes. The interface specifies the members (properties, methods, and so on) that a compliant class must have. A class is said to implement an interface when each of the members specified in the interface is present in the class. Generally, if you add code that states that a class implements an interface and then don’t include the members required by the interface, you’ll get a syntax error when you attempt to compile (or run) the code.
Class interfaces are important in multideveloper team projects to help create uniform class designs. They’re also useful in helping to pinpoint the crucial points of a class. For example, classes that do comparisons might be required to implement a Comparison interface. The Comparison interface might specify a compareTo method, which provides a way to compare, and order, two objects based on the class. So, any class that implements the Comparison interface would have to provide a compareTo method, which would compare any two objects based on the class.
Sure, programming in an object-oriented fashion encourages code that’s modular and reusable (and I’ll have more to tell you about this in a bit). But for me, the great virtue of OO is that it allows programmers to build systems that closely model the real world. In these systems, if the classes— blueprints for the objects in the systems—have been designed correctly, then programs that unleash these objects will have great power. In fact, one can use OO systems of this sort to create programs that have a virtual life of their own.
This makes OO particularly effective for dealing with situations that involve complex interactions and when you don’t really know how things will turn out. Examples include modeling financial markets and forecasting weather. One interesting (and highly OO) program that I’ve written used ideas found in Jared Diamond’s Pulitzer Prize–winning book Guns, Germs, and Steel (W. W. Norton & Company, 1999) to model the progress of human cultures. As you might suppose, each culture was implemented as an object based on a class that represented a template for human societies. The program, written in C#, tracked the progress of each culture over time and showed the results of culture clashes, such as the one between the Spanish and the Incas discussed in Professor Diamond’s book (see Figure 7-1).
Figure 7-1: Each human society is implemented as an object using a general class as a template.
This was a reasonably easy program to write once I became clear about the classes, objects, and relationships involved—and it would, I believe, have been close to impossible to write in a non-OO fashion.
The following are some of the most important concepts related to the practice of object-oriented programming:
Abstraction: Abstraction means filtering out the extraneous properties and attributes of objects so that users of the object can focus on the core properties that matter. Good OO practice encourages the appropriate use of abstraction.
Aggregation: Aggregation means the ability to create an object that’s a composite of other objects by extending or combining existing objects. Aggregation, sometimes also called containment, is a powerful way to model real-life processes and to simplify coding.
Encapsulation: Encapsulation is the process of hiding (or encapsulating) the data used by an object and granting access to it only through specific interactions with the object. This grouping of related attributes and methods is used to create a cohesive entity that’s opaque to the outside except for the specified access methods.
There are lots of real-life analogies to encapsulation. Think, for example, about requests for information from the president of the United States. If all requests for information from the president must be directed to the Press Office, then the Press Office is practicing encapsulation.
Controlling access via encapsulation is a good way to create maintainable code that has fewer bugs.
Polymorphism: From an OO viewpoint, polymorphism means the ability of two different objects to respond to the same request in their own unique ways. For example, a print text message might cause a printer object to print the text. The same message, when received by a screen object, might cause the text to be displayed on the screen.
When I was in college, I took an advanced mathematics class with a pretty peculiar rule for the final exam. Each student was allowed to bring in an 8 11 sheet of paper to the final with whatever notes on it they’d like (otherwise, the final was “closed book”). Yes, in case you’re curious, you could write on both sides of the sheet of paper!
I thought the concept was pretty bogus, but who was I to buck the system? I got a pen with the finest tip I could find and filled both sides of my sheet of paper with what I thought would be the answers to the questions on the final.
I don’t really remember how much my “cheat sheet” matched what was on the final, but I do know that I learned a great deal by creating the cheat sheet. The teacher was actually pretty smart!
In that spirit, because I’ve thrown a great deal of OO theory at you in this section, I’d like to provide summary definitions of the key concepts as if there were going to be a final exam.
|Try This at Home|| |
My suggestion to you is that at this point you shut this book and create your own OO cheat sheet. See how many OO concepts you can define. After you’ve spent 5 or 10 minutes thinking about this, you can, of course, open the book and look at my answers!
Here’s the OO cheat sheet:
A class is a template, or pattern, for objects.
An object is an aggregation of values.
To use an object, it first must be instantiated, which means that an instance of the object must be created and initialized using the constructor provided by the class .
Once you have an instance of an object, you can use the properties, methods, and events that the object provides.
A property is used to save and retrieve a value, just as variables are.
A method is used to do something, just as a function is used to do something.
An event is a special kind of function that’s triggered, or fired, in response to a specific condition, such as a button being clicked. An event handler is a placeholder that gives you a chance to execute code when the event is fired.
The key benefits of object-oriente d programming include clarity, reusability, and mo dularity. OO techniques are particularly helpful in situations that involve complex systems that may mimic real-life processes.
These benefits are partially obtained through abstraction, which helps the programmer to focus on obje ct characteristics that matter and to filter out unimportant details; encapsulation, which hides internal object data and only allows gated access to objects; and polymorphism, which lets different objects implement the same task but each in their own way.