Hour 10

Creating Your First Object

One of the more fearsome items of jargon that you'll encounter during these 24 hours is object-oriented programming. This is a complicated term for an elegant way of describing what a computer program is and how it works. Before object-oriented programming, computer programs were usually described under the simplest definition you've learned in this book: sets of instructions that are listed in a file and handled in some kind of reliable order. Whether the program is big or small, the programmer's job is largely the same--write instructions for each thing the computer must do. By thinking of a program as a collection of objects instead, you can figure out the tasks a program must accomplish and assign the tasks to the objects where they belong best.

During this hour, the following topics will be covered:

How Object-Oriented Programming Works

The programs that you create with Java can be thought of as objects just like any other objects in the world, such as nails, skateboards, Liquid Paper, glue, or 60 Minutes cohost Morley Safer. An object is made up of smaller objects--in the case of Mr. Safer, two legs, two arms, a torso, a head, and a reporter's notebook. Each object has things that make it different from other objects. Morley's legs are long and angular; they bend in the middle and end in feet. His arms end in hands and are shorter than the legs. Each object also has specific jobs it has to do. Morley's legs are used for movement and support, and his arms are used to grab things, take notes, and hail taxicabs. If you break down computer programs in the same way that you have broken down Morley Safer, you are engaging in object-oriented programming. It's a much less complicated concept than it originally sounds.

In object-oriented programming, an object contains two things: attributes and behavior. Attributes are things that describe the object and show how it is different from other objects. Behavior is what an object does.

You create objects in Java by using a class as a template. The class is a master copy of the object that is consulted to determine which attributes and behavior an object should have. The term class should be familiar to you because every Java program that you have written thus far has been called a class. Every program that you create with Java will be a class because each one could be used as a template for the creation of new objects. As an example, any Java program that uses strings is using the String class. This class contains attributes that determine what a String object is and behavior that controls what String objects can do.

With object-oriented programming, any computer program is a group of objects that work together to get something done. Some simple programs may seem as though they consist of only one object--the class file. However, even those programs are using other objects to get their work done.

Objects in Action

Consider the case of a dice-rolling program. Rolling a six-sided die is a simple thing to do in the real world--you toss a cube and check the uppermost side of the cube when it stops rolling. When you make a computer do the same thing, you can think of the die as an object. In fact, during Hour 21, "Playing Games with Java," you will be using a Die object as you teach the computer to play the dice-rolling game called craps.

A Die object could consist of the following:

When you compare a six-sided die in the real world to a Die object in a computer program, it might seem odd to ask the Die object to roll itself. Dice don't roll themselves in the real world. However, objects in object-oriented programming work for themselves whenever possible. This quality makes them more useful because you can incorporate them in other programs without having as many things to teach them. If a Die object did not know how to roll itself, for instance, every time you used that Die object somewhere you would have to create behavior to roll it.

For another example of object-oriented programming, consider the autodialer program that Matthew Broderick's character used in WarGames to find computers he could hack into. If you're unfamiliar with the term, an autodialer is software that uses a modem to dial a series of phone numbers in sequence. The purpose of such a program is to find other computers that answer their own phone, so you can call them up later to see what they are.

Using an autodialer today practically guarantees you'll be on a first-name basis with your local phone company. In the early '80s, it was a good way to be rebellious without actually leaving the house. David Lightman (Broderick) used his autodialer to look for a videogame company's private computer system. He wanted to play the new game they were working on. Instead, Lightman found a secret government computer that could play everything from chess to Global Thermonuclear War.

An autodialer, like any computer program, can be thought of as a group of objects that work together. It could be broken down into the following:

Each object exists independently of the other. The Modem object does its job without requiring any help from the Monitor object.

One of the advantages of having a completely independent Modem object is that it could be used in other programs that need modem functionality. If Broderick's character returns to hacking in WarGames 1997 after a bitter divorce from Ally Sheedy's character, he could use the Modem object as part of an elaborate ATM fraud scheme.

Another reason to use self-contained programs such as objects is that they are easier to debug. Computer programs quickly become unwieldy in size. If your program is just one big list of instructions, you can't change one part without making sure it won't damage the performance of other parts that are dependent on it. If you're debugging something like a Modem object, though, you know it's not dependent on anything else. You can focus on making sure the Modem object does the job it's supposed to do and holds the information that it needs to do its job.

For these reasons, object-oriented programming is becoming the norm in many areas of software development. Learning an object-oriented language like Java as your first programming language can be an advantage in some ways because you're not unlearning the habits of other styles of programming. The main disadvantage is that an object-oriented language can be more challenging to learn than a non-object-oriented language such as Visual Basic.

What Objects Are

As stated, objects are created by using a class of objects as a guideline. The following is an example of a class:

public class Dog {
}

Any object created from this class can't do anything because it doesn't have any attributes or behavior yet. You need to add those or this class that won't be terribly useful. You could expand the class into the following:

public class Dog {
    String name;

    public void speak() {
        System.out.println("Arf! Arf!");
    }
}

The Dog class now should be recognizable to you because it looks a lot like the programs you have written during Hours 1 through 9. The Dog class begins with a class statement, as your programs have, except that it has a public statement alongside it. The public statement means that the class is available for use by the public--in other words, by any program that wants to use Dog objects.

The first part of the Dog class creates a string variable called name. This variable is an attribute of the object; the name is one of the things that distinguishes a dog from other dogs. The second part of the Dog class is a method called speak(). This method has one statement, a System.out.println() statement that displays the text, Arf! Arf!

If you wanted to use a Dog object in a program, you would create the object much like you would create a variable. You could use the following statement:

Dog firstDog = new Dog();

This statement creates a Dog object called firstDog. You can now use the object in the program; you can set its variables and call its methods. To set the value of the name variable of the firstDog object, you could use the following statement:

firstDog.name = "Checkers";

To make this dog speak by calling the speak() method, you could use the following code:

firstDog.speak();

Like a well-trained pet, the Dog object would respond to this statement by displaying the text, Arf! Arf!

Understanding Inheritance

The final selling point to object-oriented programming is called inheritance. Inheritance is the way one object can inherit behavior and attributes from other objects that are similar to it.

When you start creating objects for use in other programs, you will find that some new objects you want are a lot like other objects that have already been developed. For example, if David Lightman does not run afoul of the law because of his ATM scheme, he might want to create an object that can handle error correction and other advanced modem features that weren't around back in 1983 when WarGames was released.

Lightman could create a new ErrorCorrectionModem object by copying the statements of the Modem object and revising them. However, if most of the behavior and attributes of ErrorCorrectionModem are the same as those of Modem, this is a lot of unnecessary work. It also means that Lightman will have to maintain two separate programs if something needs to be changed or debugged later on. Through inheritance, a programmer can create a new class of objects by defining only how it is different from an existing class. Lightman could make ErrorCorrectionModem inherit from Modem, and all he would have to write are the things that make error-correction modems different than previous modems.

The way that a class of objects inherits from another class is through the extends statement. The following is a skeleton of an ErrorCorrectionModem class that inherits from the Modem class:

class ErrorCorrectionModem extends Modem {
         // program goes here
}

Building an Inheritance Hierarchy

Inheritance enables a variety of related classes to be developed without a lot of redundant work. Inheritance can be passed down from one class to another class to another class. This system of classes is called a class hierarchy, and all of the standard classes that you can use in your Java programs are part of a hierarchy.

Understanding a hierarchy is easier if you understand what subclasses and superclasses are. A class that inherits from another class is called a subclass, and the class that it is inherited from is called a superclass. In the preceding WarGames example, the Modem class is the superclass of the ErrorCorrectionModem class, and ErrorCorrectionModem is the subclass of Modem. A class can have more than one class that inherits from it in the hierarchy--another subclass of Modem might be ISDNModem, for example, if ISDN modems have behavior or attributes that make them different from error-correcting modems. If there were a subclass of ErrorCorrectionModem, such as InternalErrorCorrectionModem, it would inherit from all the classes above it--both ErrorCorrectionModem and Modem.

The programs that you write as you are learning about Java won't use complicated class hierarchies. However, the classes that are part of the standard Java language make full use of inheritance. Understanding it is essential to making the most of the classes that come with Java. You'll learn more about inheritance during Hour 12, "Inheriting Methods from Other Classes."

Workshop: Creating an Object

To see a working example of classes and inheritance, you will create classes that represent two types of objects: dogs and Morley Safer. For the sake of simplicity, the workshop will focus on a few simple attributes and behavior for these objects:

  1. 1. Each object should have a name and be able to remember it.
  2. 2. Each object should snore when it sleeps.
  1. 3. Each object should speak in an accurate way. Although dogs and Morley Safer can remember their own names and snore in the same manner, they do not speak in the same manner.

The first two things are shared in common between dogs and Morley Safer. Because of this, you can create a superclass that both the Dog class and the MorleySafer class can inherit from. Call this class Mammal. Using your word processor, create a new file and save it as Mammal.java. Enter Listing 10.1 and save the file.

Listing 10.1. The full text of Mammal.java.


1: public class Mammal {
2:     String name;
3:
4:     public void sleep() {
5:         System.out.println("ZZZZ ZZZZZZ ZZZZ");
6:     }
7: } 


Compile this file with the javac compiler tool to produce a file called Mammal.class. Although you cannot run this program with the interpreter, you will be able to use it in other classes. You now have a Mammal class that can handle both of the things that the Dog and MorleySafer class have in common. By using the extends statement when you are creating the Dog and MorleySafer classes, you can make each of them a subclass of Mammal.

Start a new file in your word processor and save it as Dog.java. Enter Listing 10.2, and then save and compile the file.

Listing 10.2. The full text of Dog.java.


1: public class Dog extends Mammal {
2:     public void speak() {
3:         System.out.println("Arf! Arf!");
4:     }
5: } 


Create a third file with your word processor, and save it as MorleySafer.java. Enter Listing 10.3, and then save and compile the file when you're done.

Listing 10.3. The full text of MorleySafer.java.


1: public class MorleySafer extends Mammal {
2:     public void speak() {
3:         System.out.println("Can I ask you a few questions about your 1987 tax statement?");
4:     }
5: } 


Once you have compiled all three of these files with the javac compiler tool, you will have three class files: Mammal.class, Dog.class, and MorleySafer.class. However, you cannot run any of these class files at the command line with the java interpreter tool because they do not have main() blocks. You need to create a short Java program to test out the class hierarchy you have just built. Return to your word processor and create a new file called Speak.java. Enter Listing 10.4.

Listing 10.4. The full text of Speak.java.


 1: class Speak {
 2:     public static void main(String arguments[]) {
 3:         Dog doggie = new Dog();
 4:         MorleySafer morley = new MorleySafer();
 5:         doggie.name = "Cujo";
 6:         morley.name = "Morley Safer";
 7:         System.out.println("First we'll get the dog to speak:");
 8:         doggie.speak();
 9:         System.out.println("Now it's Morley's turn to speak:");
10:         morley.speak();
11:         System.out.println("Time for both to sleep:");
12:         doggie.sleep();
13:         morley.sleep();
14:     }
15: } 


Save and compile the file when you're done. When you run it, the output should resemble the following:

First we'll get the dog to speak:
Arf! Arf!
Now it's Morley's turn to speak:
Can I ask you a few questions about your 1987 tax statement?
Time for both to sleep:
ZZZZ ZZZZZZ ZZZZ
ZZZZ ZZZZZZ ZZZZ

Note the following statements in this program:

Summary

After creating your first class of objects and arranging several classes into a hierarchy, you ought to be more comfortable with the term object-oriented programming. You will be learning more about object behavior and attributes in the next two hours as you start creating more sophisticated objects.

Terms such as program, class, and object will make more sense as you have more experience with object-oriented development. It's a concept that takes some time to get used to. Once you have mastered it, you'll find that it's an effective way to design, develop, and debug computer programs.

Q&A

Q Can classes inherit from more than one class?

A
It's possible with some programming languages but not Java. Multiple inheritance is a powerful feature, but it also makes object-oriented programming a bit harder to use and to learn. Java's developers decided to limit inheritance to one superclass for any class, although a class can have numerous subclasses.

Q Why are object-oriented programs easier to debug?

A
Object-oriented programs enable you to focus on a smaller part of a computer program when figuring out where an error is happening. Because a related group of tasks are handled by the same object, you can focus on that object if the tasks aren't being performed correctly. You don't have to worry about any other parts of the program.

Q When would you want to create a class that isn't public?

A
The main time you would not want to make a class of objects available to other
programs is when the class is strictly for the use of one program you're writing. If you're creating a game program and your ReloadGun class of objects is highly specific to the game you're writing, it could be a private class. To make a class private, leave off the public statement in front of class.

Quiz

The following questions will test your knowledge of objects and the programs that use them.

Questions

1. What statement is used to enable one class to inherit from another class?

(a) inherits
(b) extends
(c) handitover

2.
Why are compiled Java programs saved with the .class file extension?

(a) Java's developers think it's a classy language.
(b) It's a subtle tribute to the world's teachers.
(c) Every Java program is a class.

3.
What are the two things that make up an object?

(a) attributes and behavior
(b) commands and data files
(c) spit and vinegar

Answers

1. b. The extends statement is used because the subclass is an extension of the attributes and behavior of the superclass and of any superclasses above that in the class hierarchy.

2.
c. Your programs will always be made up of at least one main class and any other classes that are needed.

3.
a. In a way, b is also true because commands are comparable to behavior, and data files are analogous to attributes.

Activities

If you don't object, you can extends your knowledge of this hour's topics with the following activity: