Special Effects and Game Development
in Java(TM) - Classes and Objects
by Anibal Wainstein
1.3.2 Classes and Objects
A class may be seen as a representation that may contain
many types of variables, methods and even other classes. Classes
are representations for objects. The object is the
product of the class and normally one works with the object.
Assume that we have a car and its blueprint. If we look at
the relation in views of object oriented programming then
the blueprint is the class and the car is the object. The
classes are normally located on the hard drive or the server
and they are loaded when you are going to create an object.
You create an object by reserving primary memory for it. This
is called allocating memory. In a Java program, you
always have at least one class. In strict object oriented
theory, it is only the methods in a class that may work with
the variables contained in the same class. However, in practice,
this is not always followed. The following is a class definition
of "car":
public class Car { //The variable "v" contains the speed in km/h public int v; public void drive() { //start with 10 km/h
v=10; }
public void stop()
{
v=0;
}
public void faster(int vincrease)
{
v+=vincrease;
}
public void slowDown(int vdecrease)
{
v-=vdecrease;
if (v<0) v=0;
}
}
Car |
v |
drive() |
stop() |
faster() |
slowDown() |
|
The example above is a class definition. The cells below
"Car" describes what variables (in blue) and what
methods (in cyan) that are in the class.
1.3.3 References and allocating
objects (the new command)
You communicate with an object with references (a
reference is equivalent to pointers in C++). Let us say that
we want to create an object to work with. We take the "blueprint"
we have defined in the last section and create a reference
like this:
Car onecar;
The reference "onecar" does not point anywhere
at the moment so you cannot work with it. Now we allocate
a bit of memory to the object "onecar" which will
use the class "Car" as the blueprint. At the same
time that we do this we set the reference "onecar"
to point at the object.
onecar = new Car();
Now we can reach the instance of the class "Car"
with "onecar" (an instance is another word for object):
onecar.drive();
onecar.faster(10);
onecar.slowDown(10);
onecar.stop();
By calling the methods above we manipulate the variable "v"
that represents the speed inside the "Car" object.
We can create all the instances we want of the class Car:
Car volvo = new Car();
Car ford = new Car();
volvo.drive();
ford.drive();
//increase speed by 10 km/h
volvo.faster(10);
//increase speed by 10 km/h
volvo.faster(10);
//increase speed by 30 km/h
ford.faster(30);
//decrease speed by 20 km/h
ford.slowDown(20);
Which car do you think will have the highest speed after
these calls? Note that the variable "v" in the "volvo"
object does not change when you call the "ford"
objects speed methods. Both objects are completely independent
and they each have their copy of "v".
Next Page >>
|