Java Reference
In-Depth Information
We won't go into the detail of how the class Hat is defined, since we don't need it at this point. The
lines appearing between the braces above are not code; they are actually program comments , since they
begin with two successive forwarded slashes. The compiler will ignore anything on a line that follows
two successive forward slashes in your Java programs, so you will use this to add explanations to your
programs. Generally the more useful comments you can add to your programs, the better. We will see
in Chapter 2 that there are other ways you can write comments in Java.
Each object of your class will have a particular set of values defined that characterize that particular
object. You could have an object of type CowboyHat , which might be defined by values such as
"Stetson" for the name of the hat, "White" for the color, and the size as 7.
owner: TimB
type: Stetson
color: White
size: 6
class CowboyHat
{
String owner;
String type;
String color;
int size;
Class
instances
owner: JaneD
type: Stetson
color: Gray
size: 7
}
The parameters defining an object are not necessarily fixed values though. You would expect the name
and size attributes for a particular CowboyHat object to stay fixed since hats don't usually change
their size, but you could have other attributes. You might have state for example, which could
indicate whether the hat was on or off the owner's head, or even owner , which would record the
owner's name, so the value stored as the attribute owner could be changed when the hat was sold or
otherwise transferred to someone else.
Operating on Objects
A class object is not just a collection of various items of data though. The fundamental difference
between a class and the complex data types that you find in some other languages is that a class includes
more than just data. A class specifies what you can do with an object of the class - that is, it defines the
operations that are possible on objects of the class. Clearly for objects to be of any use in a program,
you need to decide what you can do with them. This will depend on what sort of objects you are talking
about, the attributes they contain, and how you intend to use them.
To take a very simple example, if your objects were numbers, of type Integer for example, it would be
reasonable to plan for the usual arithmetic operations; add, subtract, multiply and divide, and probably a few
others you can come up with. On the other hand it would not make sense to have operations for calculating
the area of an Integer , boiling an Integer or for putting an Integer object on. There are lots of classes
where these operations would make sense, but not those dealing with integers.
Search WWH ::




Custom Search