What Are Java Classes and Objects?
When you program in Java, you work constantly with classes and objects. To understand these, close your eyes for a minute and think about what it means for something to be a chair. . . .
A chair has a seat, a back, and legs. Each seat has a shape, a color, a degree of softness, and so on. These are the properties that a chair possesses. What is described here is chairness — the notion of something being a chair. In object-oriented terminology, you’re describing the class.
Now peek over the edge of this book’s margin and take a minute to look around your room. Several chairs are in the room, and each chair is an object. Each of these objects is an example of that ethereal thing called the class. So that’s how it works — the class is the idea of chairness, and each individual chair is an object.
A class isn’t quite a collection of things. Instead, a class is the idea behind a certain kind of thing. When you talk about the class of chairs in your room, you’re talking about the fact that each chair has legs, a seat, a color, and so on.
The colors may be different for different chairs in the room, but that doesn’t matter. When you talk about a class of things, you’re focusing on the properties that each of the things possesses.
It makes sense to think of an object as being a concrete instance of a class. In fact, the official terminology is consistent with this thinking. If you write a Java program in which you define a class, each actual chair (the chair that you’re sitting on, the empty chair right next to you, and so on) is called an instance of the class.
Here’s another way to think about a class. Imagine a table displaying all three of your bank accounts.
|1011 1234 2122 0000||Credit||–471.03|
Think of the table’s column headings as a class, and think of each row of the table as an object. The table’s column headings describe the class.
According to the table’s column headings, each account has an account number, a type, and a balance. Rephrased in the terminology of object-oriented programming, each object in the class (that is, each instance of the class) has an account number, a type, and a balance.
So, the bottom row of the table is an object with account number 16-17238-13344-7. This same object has type Savings and a balance of 247.38. If you opened a new account, you would have another object, and the table would grow an additional row. The new object would be an instance of the same class.