Read an Excerpt
Chapter 5: Defining Classes
In this chapter we will explore the heart of the Java language-classes. Classes specify the objects you use in object-oriented programming. These form the basic building blocks of any Java program, as we saw in Chapter 1. Every program in Java involves classes, since the code for a program can only appear within a class definition.We will now explore the details of how a class definition is put together, how to create your own classes and how to use classes to solve your own computing problems. And in the next chapter we'll extend this to look at how object-oriented programming helps us work with related classes.
By the end of this chapter you will have learned:
- What a class is, and how you define one
- How to implement class constructors
- How to define class methods
- What method overloading is
- What a recursive method is and how it works
- How to create objects of a class
- What packages are and how you can create and use them
- What access attributes are and how you should use them in your class definitions
- When you should add the finalize() method to a class
- What native methods are
What is a Class?
As you saw in Chapter 1, a class is a prescription for a particular kind of object. We can use the class definition to create objects of that class type, that is, to create objects that incorporate all the components specified as belonging to that class.
In case that's too abstract, look back to the last chapter, where we used the String class. This is JavaSoft's ultimate definition for a string object, with every conceivable requirement built in, to make String objectsindispensable and string handling within a program easy.
In essence a class definition is very simple. There are just two kinds of element that you can include in a class definition:
variablesThe elements that differentiate one object of the class from another.
methodsThe operations you can perform for the class-these determine what you can do to, or with, objects of the class. Methods operate on the variables of the class.
The variables in a class definition can be of any of the basic types, or they can be objects of any class, including the one that you are defining.
The methods in a class definition are named, self-contained blocks of code, that typically operate on the variables that appear in the class definition. Note though, that this doesn't necessarily have to be the case, as you might have guessed from the main() methods we have written in all our examples up to now.
Variables in a Class Definition
An object of a class is also referred to as an instance of that class. When you create an object, the object will contain all the variables that were included in the class definition. However, the variables in a class definition are not all the same. There are two kinds. One kind of class variable is associated with each object uniquely-each instance of the class will have its own copy of each of these variables, with its own value assigned. These differentiate one object from another-they give an object its individuality. The other kind of class variable is associated with the class, and is shared by all objects of the class. There is only one copy of each of these kinds of variables no matter how many class objects are created.
Because this is extremely important to understand, let's summarize the two kinds of variables that you can include in your classes:
Instance variables Each object of the class will have its own copy of each of the instance variables that appear in the class definition. Each object will have its own values for each instance variable. The name 'instance variable' originates from the fact that an object is an 'instance' of a class. An instance variable is declared within the class definition in the usual way, with a type name and a variable name.
Class variablesA given class will only have one copy of each of its class variables, and these will be shared between all the objects of the class. The class variables exist even if no objects of the class have been created. They belong to the class, but they are included as part of every object of the class. If the value of a class variable is changed, the new value is available in all the objects of the class. This is quite different from instance variables where changing a value for one object does not affect the values in other objects. A class variable must be declared using the keyword static preceding the type name.
Why would you need two kinds of variables in a class definition? The instance variables are clearly necessary since they are the parameters that distinguish a particular object. The radius and the coordinates of the position of the center of the sphere are fundamental to determining how big a particular Sphere object is, and where it is in space. However, although the variable PI is a fundamental parameter for a sphere-to calculate the volume for example-it would be wasteful to store a value for PI in every object, since it is always the same. Incidentally, it is also available from the standard class Math. So one use for class variables is to hold constant values such as ? that are common to all objects of the class.
Another use for class variables is to track data values that are common to all objects of a class, and that need to be available even when no objects have been defined. For example, if you wanted to keep a count of how many objects of a class have been created in your program, you would define the variable storing the count as a class variable. It would be essential to use a class variable, because you would still want to be able to use your count variable even when no objects had been declared.
Methods in a Class Definition
The methods that you define for a class provide the actions that can be carried out using the variables specified in the class definition.
Analogous to the variables in a class definition, there are two varieties of methods, instance methods and class methods. You can execute class methods even when no objects of a class exist, whereas instance methods can only be executed in relation to a particular object, so if no objects exist, there are no instance methods to be executed. Again, like class variables, class methods are declared using the keyword static.
Since class methods can be executed when there are no objects in existence, they cannot refer to instance variables. This is quite sensible if you think about it-trying to operate with variables that might not exist is bound to cause trouble. In fact the Java compiler won't let you try. If you reference an instance variable in the code for a class method, it won't compile-you'll just get an error message.
The class Sphere might well have an instance method volume() to calculate the volume of a particular object. It might also have a class method objectCount() to return the current count of how many objects have been created. If no objects exist, you could still call this method and get the count, 0.
Note that, although instance methods are specific to objects of a class, there is only ever one copy of an instance method in memory, as it would be extremely expensive to replicate all the instance methods for each object. This raises the question as to how this is consistent with instance methods being specific to an object, but we will defer exploring this until a little later in this chapter.
Perhaps the most common use for class methods is when a class is just used to contain a bunch of methods, rather than as a specification for objects. All executable code in Java has to be within a class, but there are lots of general utility functions that you need that don't necessarily have an object association-calculating a square root, for instance, or generating a random number. For example, the mathematical functions that are implemented as class methods in the standard class Math, don't relate to class objects at all-they operate on values of the basic types. You don't need objects of type Math, you just want to use the methods from time to time, and you can do this as we saw in Chapter 2. The class Math also contains some class variables containing useful mathematical constants such as e and ?.
So, if you wanted to calculate the square root of ? you could access the class method sqrt() and the class variable PI as follows....