Data types aren't much use unless you can do things with them. For this purpose classes have methods. Fields say what a class is. Methods say what a class does. The fields and methods of a class are collectively referred to as the members of the class.

The classes you've encountered up till now have mostly had a single method, main(). However, in general classes can have many different methods that do many different things. For instance the Car class might have a method to make the car go as fast as it can. For example,

class Car {

  String licensePlate = "";    // e.g. "New York 543 A23"
  double speed        = 0.0;   // in kilometers per hour
  double maxSpeed     = 123.45; // in kilometers per hour
  // accelerate to maximum speed
  // put the pedal to the metal
  void floorIt() {
    this.speed = this.maxSpeed;  

The fields are the same as before, but now there's also a method called floorIt(). It begins with the Java keyword void which is the return type of the method. Every method must have a return type which will either be void or some data type like int, byte, float, or String. The return type says what kind of the value will be sent back to the calling method when all calculations inside the method are finished. If the return type is int, for example, you can use the method anywhere you use an int constant. If the return type is void then no value will be returned.

floorIt is the name of this method. The name is followed by two empty parentheses. Any arguments passed to the method would be passed between the parentheses, but this method has no arguments. Finally an opening brace ( { ) begins the body of the method.

There is one statement inside the method

this.speed = this.maxSpeed;

Notice that within the Car class the field names are prefixed with the keyword this to indicate that I'm referring to fields in the current object.

Finally the floorIt() method is closed with a } and the class is closed with another }.

Question: what are some other methods this class might need? Or, another way of putting it, what might you want to do with a Car object?

Previous | Next | Top | Cafe au Lait

Copyright 1997-1999 Elliotte Rusty Harold
Last Modified October 1, 1999