Next: Some basic graphics classes. Up: Using objects. Previous: None.


What is an object?

Textbook: Sections 3.1 and 3.2

The types we've seen so far - int, char, boolean, and double - are what Java calls primitive types. These are the simplest types - you might say they're the most primitive.

But programs tends to deal with more complicated things too. In our upcoming labs, we'll have programs that deal with all of the following.

We'll want to represent all these objects in our programs - and to do that, it's useful to have types so we can have variables representing the objects. Thus, Java has a whole other category of types: the object type.

The object type is called a class, and individual instances of the type are instances. For example, we might have a class named Ball for representing balls, and a program manipulating balls might want to manipulate two separate instances of this class. It could do this by declaring two variables of the Ball type.

Ball quaffle;
Ball snitch;

As you might expect, an object type is a conglomeration of data. For example, a ball bouncing around the screen has several properties: an x-coordinate, a y-coordinate, an angle of trajectory, and a speed. In this case, each piece of data would be a double, but there could be any combination. In any case, each individual ``fact'' about the object would be called an instance variable.

But, in fact, when we write programs using an object types, we'll almost never refer to instance variables directly. Instead, the class will define instance methods - basically, a method that manipulates the instance variables. Among the instance methods for the Ball class, for example, are the following.

int getTop()
Returns the y-coordinate of the ball's top.

int getLeft()
Returns the x-coordinate of the ball's left side.

void step()
Alters the ball's x- and y-coordinates according to its current trajectory.

void draw(Graphics g)
Draws the ball according to its current position on the canvas represented by g.

As with class methods, instance methods can take parameters. The last of these instance methods happens to take a Graphics object as a parameter - a class about which we'll learn more next.


Next: Some basic graphics classes. Up: Using objects. Previous: None.