Defining a Class in Java: Accounts

By Barry Burd

When you come right down to it, the differences between one account and another can be summarized as values of variables in Java code. Maybe there’s a variable named balance. For one person, the value of a variable like balance is 24.02.

For another, the value of balance is 55.63. The question is, when writing a computer program to deal with accounts, how do you separate one balance variable from another balance variable?

The answer is to create two separate objects. Let one balance variable live inside one of the objects and let the other balance variable live inside the other object.

While you’re at it, put a name variable and an address variable in each of the objects. And there you have it — two objects, and each object represents an account. More precisely, each object is an instance of the Account class. (See this figure.)

image0.jpg

So far, so good. However, you still haven’t solved the original problem. In your computer program, how do you refer to one balance variable, as opposed to another balance variable? Well, you have two objects sitting around, so maybe you have variables to refer to these two objects.

Create one variable named myAccount and another variable named yourAccount. The myAccount variable refers to one object (my instance of the Account class) with all the stuff that’s inside it. To refer to this balance, write

myAccount.balance

To refer to this name, write

myAccount.name

Then yourAccount.balance refers to the value in your object’s balance variable, and yourAccount.name refers to the value of your object’s name variable. To tell the computer how much one has in one account, you can write

myAccount.balance = 24.02;

To display your name on the screen, you can write

out.println(yourAccount.name);

These ideas come together in these example listings.

public class Account {
    String name;
    String address;
    double balance;
}

The Account class in defines what it means to be an Account. In particular, it tells you that each of the Account class’s instances has three variables — name, address, and balance. This is consistent with the information in the figure. Java programmers have a special name for variables of this kind (variables that belong to instances of classes). Each of these variables — name, address, and balance — is called a field.

A variable declared inside a class but not inside any particular method is a field. In the listing, the variables name, address, and balance are fields. Another name for a field is an instance variable.

Can you really define a complete Java class with only four lines of code (give or take a curly brace)? You certainly can. In fact, the Account class in this listing is quite representative of what Java programmers think of when they think class. A class is a grouping of existing things. In the Account class, those existing things are two String values and a double value.