4. A World of Objects

Key concepts

  1. Objects: the things that inhabit our world
  2. Naming objects
  3. Creating objects
  4. Sending messages to objects
  5. The interpreter: our first tool

Introduction

Java provides us with a language that allows us to express an object-oriented view of the world. It allows us to build models or simulations of real-world - or even non-real-world - entities and environments. The fundamental unit of modeling is called the object.

What's an object? The answer is simple, really. Objects in Java are very similar to the things we think of as objects: chairs, tables, cars, people, students, files, desks, drawers, money, bank accounts, and so on. Many people argue that object-oriented programming is more difficult for the beginning programmer to master, because students must understand the supposedly difficult concepts of the "object." However, we take the opposite view. Thinking about objects in computer programs is as natural as thinking about objects in the real world. It is something that we as individuals have done since a very young age. Furthermore, thinking about the world as consisting of objects is deeply rooted in the Western cultural tradition. Many of the ideas first explored by Plato and Aristotle over two thousand years ago have manifested themselves today in the technology of object-oriented programming.

Objects often (usually) are made up of other objects. In fact, very few objects are primitive -- most objects consist of other objects. Humans have organs; organs have tissues; tissues have cells; cells have DNA, proteins, mitochondria, and so on. Offices have desks; desks have drawers; drawers can have contents inside of them. Composition of objects is a central theme that we'll revisit throughout this study.

Let's take a detour and enrich our understanding of language by looking at how we often use it to describe the world around us. While this discussion may seem as if it couldn't be further from learning how to program a computer, it turns out to provide the fundamental basis for nearly everything we'll talk about for the rest of our study. Why? Because building an object-oriented computer program is all about using a simple language (such as Java, which is much simpler and less powerful than our own, natural language) to define a system of things and their relationships. We shall see that it is not at all radically different from the way we use language every day.

Things/Objects

Imagine that I have a pet cat, named "Henry". Henry is a real, physical being, with certain qualities, such as age, weight, size, and so on. Henry is composed of other things, such as muscles, organs, and blood. Henry is also an active entity: he can consume food, make sounds, and walk about. My neighbor may also have a pet cat, named "Natasha". Natasha and Henry are both cats, but they are distinct entities. It seems somehow degrading to say that both Henry and Natasha are objects, but we can view them as such.

Names and Meaning

The name "Henry", at least in the context of my household, refers to the being or thing that inhabits my home, that walks on four legs, meows when it is hungry and so on. We say that the meaning of the word "Henry" is the object that it refers to, namely that being which inhabits my home. The word or name "Natasha" refers, on the other hand, to a similar being that inhabits my neighbor's home. The meaning of a word is the object it refers to. In language, we may have multiple words that refer to the same object. For instance, the words "George" and "President" are words that refer to the same object -- the president of the United States at the time of this writing.

Concepts

Now let's think about the word "cat" for a moment. What is the meaning of that word? If our view of meaning is that the meaning of a word is the thing that it refers to, then we must ask, What does the word "cat" refer to? It certainly doesn't refer (when used in the general sense) to any particular cat. Instead, it seems to refer to the set of qualities that all cats have in common. It refers to the collection of knowlege that we have about Natasha, Henry, and all other cats. The word "cat" refers to the concept of cat, rather than any particular cat. A concept is a definition or a description of a set of objects. Concepts exist only in our minds -- they do not have a real, physical presence.

Must objects be physical things?

At first glance, it appears that all Objects (as opposed to Concepts) have real, physical qualities. Think about chairs, cars, tables, people. These are all objects that inhabit our world, and they are all physical things. Does this statement hold true for all objects? To answer this question, think about the number seven. Is it an object, concept, or something else altogether? Ask yourself what does the word "seven" mean? What sort of thing does it refer to? It refers to a property, a quality and nothing more. It refers to a property that is shared by Snow White's Dwarves, the days of the week, and the Deadly Sins. The number seven refers to an object as surely as the name "Henry" refers to the object that is my cat. It just so happens, however, that this particular object is a pure abstraction. It exists only in our minds. Seven is a quantity, a number. It is a particular instantiation of the concept "Number" or "Quantity". Put another way, the relationship between "Henry" and "Cat" is exactly the same as that between "Seven" and "Number". Henry and Seven are names that we have given to particular instances of a given concept. The important implication is that objects do not necessarily have to be concrete, physical things. While it is easiest for us to conceive of objects that have real, physical properities we must accept that there are objects that exist only in our minds, such as numbers.

Are Concepts Objects?

The answer to this question must be yes, because concepts can be named, talked about, described, and manipulated in (almost) the same way that real, physical objects can. Of course, we can't measure how much the concept "Cat" weighs, or see it's color, but you and I can have a conversation about cats (in general), and we can refine our understanding of them (perhaps by distinguishing between house cats and wild cats). This ability to create, learn, and manipulate concepts in our minds is a faculty that makes us distinctly human.

It is true that there is a difference between concepts and objects -- concepts are special sorts of objects that have descriptive and generative powers. They describe a set of objects that all share a certain makeup and qualities. They can also be used to generate new objects. It's easiest to see this with respect to Numbers. Understanding the concept of Number allows us, for instance, to generate all kinds of numbers, like 7, 42, or 3.1415. These differences do not mean that concepts themselves are not objects.

A Brain Teaser

If concepts are objects, and all objects are instances of a particular concept, then what concept are concepts themselves instances of?

From Language to Java

Let's briefly review what we know about how we think about and talk about the world around us. Objects are the things that inhabit our world. They have qualities and often consist of other objects. A car, for example, consists of body parts, an engine, wheels, and so on. It also has qualities such as color. An engine has qualities such as size and power output. We may also think of Objects as being able to perform certain kinds of activities. I, for example, can write, speak, drive a car, take a shower, and so on. A dog, for example, can bark, eat, roll over, and sleep. All Objects are particular instances of some Concept. Concepts are special kinds of objects that have descriptive and generative power. They describe a set of objects that all share the same makeup; and, particularly in the case of abstract entities such as numbers, they can be used to generate new instances of themselves.

Java is a language which is far less descriptive, yet much more formal than our own language. That is, because we use Java to communicate with a machine, we must be totally explicit in what we say, and we must follow certain rules for how we say things. Java allows us, above all, to define Concepts, create Objects that are instances of those Concepts, and manipulate those Objects.

The terminology used in Java differs slightly from that which we have introduced above. The term object is identical; it is a thing. In Java, we use the term class instead of the word concept though. It's easy to remember this word if you remember that a concept describes a class (or set) of things. Our concept for "car" describes a set of things that are all cars. We will also use the word type as a synonym for class. There is actually a technical difference between the two terms, but for now we'll treat them as the same. Finally, just as we think of many real-world objects as being able to perform activities, Java objects can be "active" as well. In Java, if an object knows how to perform a certain activity (for instance, to drive a car) we say that it has a method. We can ask an object to perform an activity for us by sending it a message.

Note that in Java, all objects can have methods, that is, they may know how to perform certain actions for us. You should think of every object in Java as being "animated" or "alive". This ability to animate objects is what gives Java a special power: we can use it to define classes of objects, create objects of those classes, and finally ask those objects to do things for us. In Java everything is make-believe. We may animate everything. In animating all of our objects, we give them life. Part of being a good Java programmer is to imagine a world in which all objects are "smart", in which all objects can perform tasks on our behalf. Leaving behind the constraints of real-world limitations, and entering this make-believe world of animated objects allows us to create powerful systems of intercommunicating, interacting objects.

We will now proceed to re-introduce the fundamental concepts we've discussed above, but in the context of the Java language. At each step, it's important to think about the ideas we've discussed above. Think about how you consider objects, concepts, names, and so on in the real world, using real language. If you can do this, you will win most of the battle of becomming a good programmer. To be a good programmer is to know what you want to say. Once you know that, figuring out how to say it is almost mechanical. Many beginning programmers become obsessed or overwhelmed with how to say certain things in Java, when they haven't really even figured out what they want to be saying. You are already good at seeing the world in terms of objects, names, activities, and concepts. Leverage that skill as you step into a new way of expressing your ideas.

Naming Things

In our language, we've seen the use of words to name things. The word "Henry" names my cat. We say that the name "Henry" refers to the animal (a cat) who is my pet. In pictures, we might draw the relationship between the word "Henry" and the pet as follows:

The meaning of a word is the thing that it refers to. It's OK to have two names that mean the same thing. For instance, I might also call my cat "Beast" sometimes, which would result in this picture:

Notice that in this particular context, we have two names, "Henry" and "Beast" that both refer to the same object, my cat.

Simple objects

Simple objects are those that do not consist of other objects. Because nearly every program manipulates numbers in some way, Java provides us with a few different kinds of numbers, which will be our first example of Java objects. You should think of numbers in Java the same way we think of numbers in real life. A number is a quantity. It is an abstract and immutable thing. For instance, the quantity of wheels on a bicycle is the same as the quantity of wheels on a motorcycle. We have a special name for that quantity: "two." It's easy to confuse the name (in this case "two") with the actual quantity. Over the course of history, we have devised numbering systems, which allow us to conveniently name quantities. Mostly we are familiar with decimal numerals, but there are many other systems for naming quantities, including Roman numerals, binary, hexadecimal, and so on. We might draw the situation as follows:

Notice that both the names indicate the same object, which is a quantity. Pretty much all of your intuitions and understanding of numbers apply equally in the Java world. In Java we may express numbers literally and give interesting names to them:

int    score = 59;
double todaysTemperature = 67.4;
We'll use two of the different kinds of numbers provided by the Java language throughout this text: we'll use an int when we want to represent integral values; we'll use a double to represent rational values.

Throughout this study, we'll draw pictures to help understand and express the relationships between the things in our programs. Let's draw one:

The above picture shows the name "score" as referencing or denoting (with the arrow) a thing, which in this case is a quantity. Above, we represented a quantity as a cloud (or a blob), to differentiate it from its name (in that example, "3" or "III"). We could have used a blob in this picture as well, but they're not terribly descriptive. So we'll just represent quantities by their common names -- in this case, 59. The way to read a picture like the above is: "The name 'score' refers to the quantity (or number) 59."

The above example also introduces us to our first pattern, which is a pattern for naming things. Sometimes, we'll also call this binding a name to a value.

<The kind of thing> <the name> = <the thing we're naming>;

Notice that Java is sensitive to case when we write names. In other words, the name score and Score are not the same name in Java. Furthermore, Java imposes some restrictions on the legal letters in our names, which we also call identifiers sometimes. The rule is essentially that names must begin with either a '_' or a lower or upper case 'a' through 'z' character. The rest of the letters can consist of lower and upper case 'a' through 'z', '0' through '9' and '_'.

Another useful primitive object is the char, which is used to represent individual characters, such as 'b'. Here are a few examples of characters in use:

char letterGrade = 'A';
char middleInitial = 'R';
char section = 'b';
Finally, Java also provides us with a kind of thing called boolean, which we can use to talk about the truth or falsehood, for instance:
boolean rainingInSeattle = true;
boolean rainingInLosAngeles = false;
A boolean can have just one of two values, true or false. We can name these values directly in Java, just like we can name integer values directly.

Some shapes.

Suppose we want to represent some shapes in Java. Let's imagine for the time being that someone has provided us with classes that we can use to represent shapes such as rectangles and circles. Suppose that the properties of a circle are the position of its center and a radius. Suppose that the properties of a rectangle are the position of its upper left hand corner and a width and a height. We might create and name some shapes as follows:
Circle theMoon = new Circle(100, 200, 25);
Rectangle aBox = new Rectangle(30, 40, 10, 20);
Note the special word "new" used above. This is the way we ask the machine to create a new instance of an object for us. Why don't we need to say new when we use numbers? In a way, we never need to create new numbers: imagine that the Java world is inhabited by numbers in much the same way as our own and we may just name them and use them at will.

Lets draw some pictures of our new objects:

Let's look at naming in a little more detail. We say that a name refers to an object. For this reason, we can have multiple names that refer to the same object. For instance, the names "Mom" and "Ellen" may both refer to the same person, in this case, my mother. Let's look at a Java example:

Rectangle aBox = new Rectangle(30, 40, 10, 20);
Rectangle theSameBox = aBox;
Here's the resulting picture we might draw:

Finally, we can also send some messages to these objects:

 
int area = theMoon.area();
aBox.move(10, 15);
The first statement is asking the moon to compute its area, and giving the returned value a name. The second statement is asking the box to move a certain distance in the X and Y directions. We will often speak of objects as having methods. A method is a message that the object understands. For instance, we might say that a rectangle object has the move method. The basic pattern for sending a message to an object is the following:
<object-name>.<message-name>(<some information>);
We sometimes call the object that is receiving the message the receiver. It's useful to step back into real language for a moment to get a handle on this particular bit of syntax. Look at the following English sentence:
Bob eats pizza.
At some point, our language teachers totured us with the exercise of diagramming sentences, that is, breaking them down into their constituent parts. Let's do that to the above sentence:
Bob [subject] eats [verb] pizza [object]
Pretty easy. This pattern is as fundamental to sentences in the languages that humans speak as it is fundamental to Java. In Java, the receiver object is just the "subject" of the sentence. The message we send to the object is the verb or verb clause. In fact, you'll notice that method names are almost always verb clauses. Finally, the information that we send along with the message is the "object" of the sentence. Java just happens to use a different syntax (a different way of writing) to express these kinds of sentences. We could imagine rewriting the above sentence in a more Java-oriented way:
Bob.eat(pizza);

Text Strings

Most programs manipulate text in one form or another. Because of this, Java provides us with a class that we can use to represent and manipulate text. It's called a String.
String name = "Billy";
We surround the literal representation of the string in double quotes to distinguish it as an object we wish to use. Note that we use double quotes to write Strings but single quotes for characters. You can also send Strings messages, for instance:
int lengthOfName = name.length();
String upperCaseName = name.toUpperCase();
String newName = name.replace('B', 'W');

A Collection.

Java also provides us with kinds of objects that can maintain a collection of other objects. In much the same way as a drawer might hold a collection of pens, pencils, or clothing, a collection in Java can contain other objects. One important type is called the ArrayList. Here's an example:
ArrayList classList = new ArrayList();
classList.add("Bob");
classList.add("Ellen");
classList.add("Johanna");
The above collection now contains three objects, which are all Strings, used to represent the name of three students. How do we figure out who has the longest name? We don't know how to do this in Java yet, and won't for a few more lessons, but you already know how to do this. Given a real class list, think about how you might give a well-defined set of instructions, or algorithm, for finding the longest name.

The Interpreter

Now we'll introduce the interpreter, an important tool for experimenting with the Java language. An interpreter is like a real world language interpreter. Suppose that you don't know how to speak Spanish. If you needed to have a conversation with a Spanish speaker, an interpreter might assist you by listening to each question and answer and translating them into the appropriate language for the benefit of the other party. A Java interpreter does just that. You type a phrase at it, and it translates it into another representation that can be understood by the machine (computer), asks the machine to evaluate what you have typed, and prints the response. An example interaction may look like this (phrases typed by the user are in bold):
prompt> String name = "John";
prompt> name
"John"
prompt> String upperName = name.toUpperCase();
prompt> upperName
"JOHN"
prompt> name.length() + 10
14

Patterns we've learned

  1. Naming
  2. Sending messages
  3. Creating new objects

Ben Dugan & UW-CSE, Copyright (c) 2001.