Calling Instance Methods
The documentation below is for a
Treadmill class used at a gym.| Method header | Description |
|---|---|
public Treadmill(int speed) | Creates a treadmill running at speed kilometers per hour. |
public void faster(int amount) | Raises this treadmill's speed by amount. |
public void stop() | Sets this treadmill's speed to 0. |
public int getSpeed() | Returns this treadmill's speed. |
The object before the dot
The first row is the constructor. None of the three method headers below it says
static, so they're instance methods. Each call names an object, then a dot, then the method.Treadmill left = new Treadmill(5);
Treadmill right = new Treadmill(5);
left.faster(3);
System.out.println(left.getSpeed());
System.out.println(right.getSpeed());
This prints 8 and then 5. The call
left.faster(3) works on the object left refers to, and only that treadmill speeds up. The two treadmills started with the same speed, but each object keeps its own, and a call reaches only the object named before its dot.Using what a call returns
The rules for
void and non-void methods are the ones from method signatures. right.stop(); is a complete statement, and int s = right.stop(); doesn't compile, because stop returns nothing. A call to getSpeed returns an int, so it can be stored or used in an expression, as in left.getSpeed() + right.getSpeed().A class name can't stand in front of an instance method.
Treadmill.getSpeed() doesn't compile, since there would be no particular treadmill to ask.A call on a returned object
A method can return a reference to an object, and a call can be made on that object right away. The gym also has a
Runner class. Its constructor takes a speed and creates the runner's own treadmill running at that speed, and its method public Treadmill getMachine() returns that treadmill.Runner kai = new Runner(7);
System.out.println(kai.getMachine().getSpeed());
Java evaluates from the left.
kai.getMachine() returns a reference to Kai's treadmill, and getSpeed() is then called on that treadmill, so the line prints 7.Calls on null
A reference variable that holds
null refers to no object, so there's no object to call a method on.Treadmill spare = null;
System.out.println(spare.getSpeed());
This compiles, since
spare has type Treadmill and the class has a getSpeed method. When the second line runs, though, spare holds no reference, and Java throws a NullPointerException. The program stops on that line, and nothing is printed by it.