Calling Instance Methods
How to ask an object to do something: the dot operator, how instance methods use and change an object's own data, how to use their return values, and why calling a method through null fails.
Instance methods are called on objects of the class. They work with the data stored in the particular object they are called on, so the same method can give different results for different objects. The dot operator is used along with the object name to call them: bottle.drink(250). Some instance methods change the object's state; others report information about it through a return value. Because an instance method needs an object, calling one through a null reference results in a NullPointerException.
1Methods That Belong to Objects
An object combines data with the behaviors that use that data. A Bottle object stores its capacity and the amount of water in it, and its instance methods, fill, drink, getAmount, spaceLeft, and isEmpty, read or change those values. An instance method's header has no static keyword, which signals that it needs an object to work on.
When a program has several objects of the same class, each call must say which object should act. a.drink(200) asks the bottle referred to by a to drink; the bottle referred to by b is not involved. This is what makes objects useful: the class defines the behavior once, and each object applies it to its own data.
You have used instance methods since the first String: word.length() asks a particular string for its length. Every class you meet, whether from the library or written by a teammate, works the same way.
| Kind of instance method | Example | How the call is used |
|---|---|---|
| void (changes state) | bottle.drink(120); | A statement by itself |
| Returns a number | bottle.getAmount() | Stored, printed, or used in arithmetic |
| Returns a boolean | bottle.isEmpty() | Printed or used in a condition |
| Returns an object | word.substring(4) | Stored, printed, or used to call another method |
2The Dot Operator
The dot operator is used along with the object name to call instance methods. The general form is objectReference.methodName(arguments). The expression before the dot must evaluate to a reference to an object; it is usually a variable name, but it can be any expression that produces an object, including another method call that returns an object.
After the dot comes the method name and the argument list in parentheses, which follow the same rules as any method call: the arguments must match the method's parameter list in number, order, and type. Parentheses are required even when there are no arguments, as in bottle.fill(); leaving them off does not call the method.
Calling a Method on the Result of Another
When a method returns an object, another method can be called on that result. Predict the output.
String word = "telescope";
System.out.println(word.substring(4));
System.out.println(word.substring(4).length());
System.out.println(word.substring(4).indexOf("o"));
System.out.println(word);
scope
5
2
telescope
- 1
word.substring(4)returns a newString, "scope". - 2Chaining.
.length()is then called on "scope": 5. - 3
.indexOf("o")on "scope" finds "o" at index 2. - 4The original is unchanged.
wordstill refers to "telescope"; eachsubstringcall built a new string.
bottle.getAmount without parentheses is not a method call and does not compile in an expression such as int x = bottle.getAmount;. Every call needs parentheses, even when the method takes no arguments.
3Changing an Object's State
Many instance methods exist to change the object they are called on. fill() sets the amount to the capacity; drink(120) lowers it by 120. Such methods are often void: they return nothing, and their whole purpose is the change they make. A call to a void method is a statement by itself.
Because the object keeps its state between calls, a sequence of calls builds on itself. Tracing such code means keeping track of each object's attributes and updating them after every call, as in the table below. Methods may also have preconditions: drink expects that the bottle holds at least the amount requested, and it is the caller's job to respect that.
| Statement | amount | Value printed |
|---|---|---|
| Bottle bottle = new Bottle(500); | 0 | |
| bottle.fill(); | 500 | |
| bottle.drink(120); | 380 | |
| bottle.drink(80); | 300 | |
| println(bottle.getAmount()); | 300 | 300 |
| println(bottle.spaceLeft()); | 300 | 200 |
Tracing an Object Through Several Calls
The Bottle class is given. Predict the output.
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
300
200
- 1Construction. Capacity 500, amount 0.
- 2
fill(). Amount becomes 500. - 3Two
drinkcalls. 500 − 120 = 380, then 380 − 80 = 300. - 4Getters.
getAmount()returns 300;spaceLeft()returns 500 − 300 = 200.
An object remembers what earlier calls did. After fill() and two drink calls, the amount reflects all three. When predicting output, update the object's state after every call, in order, rather than reasoning about each call on its own.
4Using Return Values
Non-void instance methods return information about the object. getAmount() returns an int, isEmpty() returns a boolean, and a String's substring returns a new String. As with any non-void method, the result must be stored in a variable or used as part of an expression to be useful.
Methods that only report information, often named with get or is, usually leave the object unchanged, so calling them several times gives the same answer until some other method changes the state. Calling one as a statement by itself compiles, but the returned value is discarded and the line accomplishes nothing.
Using Results From Instance Methods
Predict the output.
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
1050
400
- 1After the calls,
aholds 300 andbholds 750 (Figure 1). - 2Combining return values.
a.getAmount() + b.getAmount()is 300 + 750 = 1050. - 3A call inside arithmetic.
a.spaceLeft()is 200, so the expression is 400.
Asking an Object a Yes-or-No Question
Predict the output.
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
true
false
true 0
- 1New bottle. Amount 0, so
isEmpty()returnstrue. - 2After
fill(). Amount 250:false. - 3After drinking 250. Amount 0 again:
true, and the getter confirms 0.
boolean report facts about an object's current state.A Call Whose Result Is Thrown Away
Predict the output. Which line has no visible effect?
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
600
- 1
jug.spaceLeft();computes 0 and returns it, but nothing stores or prints it, and the method does not change the bottle. The line has no effect. - 2
jug.drink(400);is a void method that changes the object's state: 1000 − 400 = 600. - 3The difference. Calling a void method as a statement is normal, because its purpose is its effect. Calling a non-void method as a statement throws its result away.
5Instance Methods Versus Class Methods
The expression before the dot tells you which kind of method is being called. Class methods, marked static, are called with the class name, as in Math.sqrt(49), because they do not depend on any object. Instance methods are called with an object reference, as in bottle.getAmount(), because their result depends on that object's data.
Mixing these up causes compile errors. Bottle.getAmount() fails because no bottle is specified; Java reports that a non-static method cannot be referenced from a static context. When reading documentation, check each method header for static to decide how to call it.
Using the Class Name for an Instance Method
Explain the compile error.
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
- 1
getAmountis an instance method. It has nostatickeyword, and its answer depends on a particular bottle. - 2
Bottle.getAmount()names no bottle. Java cannot know whose amount to return, so it reports that a non-static method cannot be referenced from a static context. - 3Fix. Call it on an object:
bottle.getAmount().
String.length() and Bottle.getAmount() do not compile: there is no particular string or bottle to ask. Create or obtain an object first, then call the method on it: word.length(), bottle.getAmount().
6Calling a Method Through null
A method call on a null reference will result in a NullPointerException. The compiler cannot detect this in advance, because whether a variable holds null is known only when the program runs. The program compiles, runs normally until the call, and then stops.
Common causes include declaring a variable without creating an object, setting a variable to null earlier and forgetting, or using a method's result that turned out to be null. The remedy is always the same: make sure the reference refers to an actual object before calling methods through it.
null reference will result in a NullPointerException.| Call | Result |
|---|---|
bottle.getAmount() where bottle refers to an object | Runs on that object |
Bottle.getAmount() | Compile-time error: instance method needs an object |
spare.getAmount() where spare is null | NullPointerException at run time |
Math.sqrt(49) | Class method: called with the class name |
Calling a Method on a null Reference
What happens when this program runs?
public class Bottle
{
private int capacity;
private int amount;
public Bottle(int cap)
{
capacity = cap;
amount = 0;
}
public void fill()
{
amount = capacity;
}
/** Precondition: ml <= the amount currently in the bottle */
public void drink(int ml)
{
amount = amount - ml;
}
public int getAmount()
{
return amount;
}
public int spaceLeft()
{
return capacity - amount;
}
public boolean isEmpty()
{
return amount == 0;
}
}
- 1The code compiles.
sparehas typeBottle, andBottlehas afillmethod. - 2The first line prints.
- 3
spare.fill()fails.spareholdsnull, so there is no bottle to fill. Java throws aNullPointerException, and the last line never runs. - 4Fix. Create the object first:
Bottle spare = new Bottle(500);.
checking the spare, then stops with a NullPointerException. A method call on a null reference always fails at run time.Code that calls a method through a null reference compiles without complaint. The NullPointerException appears only at run time. When tracing, check that every variable before a dot actually refers to an object at that moment.
Four Habits for Instance Methods
1. Object, Dot, Method
The reference before the dot chooses which object acts.
2. Track State
Each call starts from the state earlier calls left behind.
3. Use Every Result
Store or use what non-void methods return.
4. No Calls Through null
A null reference before the dot means a NullPointerException.
Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods, and each call works with the attributes of the object it is called on, either changing them or reporting information through a return value that must be stored or used. Instance methods cannot be called with the class name alone, and a method call on a null reference will result in a NullPointerException.