System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə21/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   17   18   19   20   21   22   23   24   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )

members of the class. The data members are also referred to as instance variables.
The General Form of a Class


The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by
specifying the instance variables that it contains and the methods that operate on them.
Although very simple classes might contain only methods or only instance variables,
most real­world classes contain both.
A class is created by using the keyword class. A simplified general form of a class
definition is shown here:
class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
Although there is no syntactic rule that enforces it, a well­designed class should define
one and only one logical entity. For example, a class that stores names and telephone
numbers will not normally also store information about the stock market, average
rainfall, sunspot cycles, or other unrelated information. The point here is that a well­
designed class groups logically connected information. Putting unrelated information
into the same class will quickly destructure your code!
Up to this point, the classes that we have been using have had only one method: main(
). Soon you will see how to create others. However, notice that the general form of a
class does not specify a main( ) method. A main( ) method is required only if that
class is the starting point for your program. Also, some types of Java applications don’t


require a main( ).
Defining a Class
To illustrate classes, we will develop a class that encapsulates information about
vehicles, such as cars, vans, and trucks. This class is called Vehicle, and it will store
three items of information about a vehicle: the number of passengers that it can carry,
its fuel capacity, and its average fuel consumption (in miles per gallon).
The first version of Vehicle is shown next. It defines three instance variables:
passengers, fuelcap, and mpg. Notice that Vehicle does not contain any methods.
Thus, it is currently a data­only class. (Subsequent sections will add methods to it.)
A class definition creates a new data type. In this case, the new data type is called
Vehicle. You will use this name to declare objects of type Vehicle. Remember that a
class declaration is only a type description; it does not create an actual object. Thus,
the preceding code does not cause any objects of type Vehicle to come into existence.
To actually create a Vehicle object, you will use a statement like the following:
After this statement executes, minivan refers to an instance of Vehicle. Thus, it will
have “physical” reality. For the moment, don’t worry about the details of this statement.
Each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class. Thus, every Vehicle object will
contain its own copies of the instance variables passengers, fuelcap, and mpg. To
access these variables, you will use the dot (.) operator. The dot operator links the
name of an object with the name of a member. The general form of the dot operator is
shown here:
object.member
Thus, the object is specified on the left, and the member is put on the right. For
example, to assign the fuelcap variable of minivan the value 16, use the following


statement:
In general, you can use the dot operator to access both instance variables and methods.
Here is a complete program that uses the Vehicle class:
To try this program, you can put both the Vehicle and VehicleDemo classes in the
same source file. For example, you could call the file that contains this program
VehicleDemo.java. This name makes sense because the main( ) method is in the
class called VehicleDemo, not the class called Vehicle. Either class can be the first
one in the file. When you compile this program using javac, you will find that two
.class files have been created, one for Vehicle and one for VehicleDemo. The Java
compiler automatically puts each class into its own .class file. It is important to
understand that it is not necessary for both the Vehicle and the VehicleDemo class
to be in the same source file. You could put each class in its own file, called
Vehicle.java and VehicleDemo.java, respectively. If you do this, you can still


compile the program by compiling VehicleDemo.java.
To run this program, you must execute VehicleDemo.class. The following output is
displayed:
Before moving on, let’s review a fundamental principle: each object has its own copies
of the instance variables defined by its class. Thus, the contents of the variables in one
object can differ from the contents of the variables in another. There is no connection
between the two objects except for the fact that they are both objects of the same type.
For example, if you have two Vehicle objects, each has its own copy of passengers,
fuelcap, and mpg, and the contents of these can differ between the two objects. The
following program demonstrates this fact. (Notice that the class with main( ) is now
called TwoVehicles.)


The output produced by this program is shown here:
As you can see, minivan’s data is completely separate from the data contained in
sportscar. The following illustration depicts this situation.


HOW OBJECTS ARE CREATED
In the preceding programs, the following line was used to declare an object of type
Vehicle:
This declaration performs two functions. First, it declares a variable called minivan of
the class type Vehicle. This variable does not define an object. Instead, it is simply a
variable that can refer to an object. Second, the declaration creates an instance of the
object and assigns to minivan a reference to that object. This is done by using the new
operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, essentially, the address in
memory of the object allocated by new. This reference is then stored in a variable.
Thus, in Java, all class objects must be dynamically allocated.
The two steps combined in the preceding statement can be rewritten like this to show
each step individually:
The first line declares minivan as a reference to an object of type Vehicle. Thus,
minivan is a variable that can refer to an object, but it is not an object itself. At this
point, minivan does not refer to an object. The next line creates a new Vehicle object
and assigns a reference to it to minivan. Now, minivan is linked with an object.
REFERENCE VARIABLES AND ASSIGNMENT


In an assignment operation, object reference variables act differently than do variables
of a primitive type, such as int. When you assign one primitive­type variable to
another, the situation is straightforward. The variable on the left receives a copy of the
value of the variable on the right. When you assign one object reference variable to
another, the situation is a bit more complicated because you are changing the object
that the reference variable refers to. The effect of this difference can cause some
counterintuitive results. For example, consider the following fragment:
At first glance, it is easy to think that car1 and car2 refer to different objects, but this is
not the case. Instead, car1 and car2 will both refer to the same object. The assignment
of car1 to car2 simply makes car2 refer to the same object as does car1. Thus, the
object can be acted upon by either car1 or car2. For example, after the assignment
executes, both of these println( ) statements
display the same value: 26.
Although car1 and car2 both refer to the same object, they are not linked in any other
way. For example, a subsequent assignment to car2 simply changes the object to which
car2 refers. For example:
After this sequence executes, car2 refers to the same object as car3. The object
referred to by car1 is unchanged.
METHODS
As explained, instance variables and methods are constituents of classes. So far, the
Vehicle class contains data, but no methods. Although data­only classes are perfectly


valid, most classes will have methods. Methods are subroutines that manipulate the
data defined by the class and, in many cases, provide access to that data. In most cases,
other parts of your program will interact with a class through its methods.
A method contains one or more statements. In well­written Java code, each method
performs only one task. Each method has a name, and it is this name that is used to call
the method. In general, you can give a method whatever name you please. However,
remember that main( ) is reserved for the method that begins execution of your
program. Also, don’t use Java’s keywords for method names.
When denoting methods in text, this book has used and will continue to use a
convention that has become common when writing about Java. A method will have
parentheses after its name. For example, if a method’s name is getval, it will be written
getval( ) when its name is used in a sentence. This notation will help you distinguish
variable names from method names in this book.
The general form of a method is shown here:

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   17   18   19   20   21   22   23   24   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə