TOPIC 1.14 · STUDY
Calling Instance Methods
An instance method runs on one object: object.method(arguments). That call uses the receiver's data. A void method performs a task and returns nothing to assign. A non-void method returns a value. Do not write ClassName.method for an instance method.
1.14.A
Calling instance methods
An instance method is called on a specific object. Write the reference, a dot, the method name, and any arguments in parentheses: object.method(arguments). The object named before the dot is the receiver. The call uses that object's data, not another object's data.
Do not write ClassName.method for an instance method. The class name alone is not a receiver. You need a constructed object whose reference appears before the dot.
A void method performs a task and does not give back a value you can assign to a variable. A non-void method returns a value you can store, print, or use in an expression. The TicketBook class below is supplied so you can see both kinds of calls. You do not need to write the class yourself for this topic.
class TicketBook {
private int pages;
public TicketBook(int start) {
pages = start;
}
public void tear(int n) {
pages -= n;
}
public int left() {
return pages;
}
}
TicketBook desk = new TicketBook(24);
TicketBook shelf = new TicketBook(24);
desk.tear(3);
System.out.print(desk.left() + "," + shelf.left());
desk and shelf are two separate TicketBook objects, each starting at 24 pages. tear is void: it updates the receiver and returns nothing, so you cannot write int x = desk.tear(3);. left returns an int. After desk.tear(3), desk has 21 pages and shelf is still 24, so the print is 21,24.
The tear call is aimed at desk only. shelf is a different object and stays at 24.
Calling an instance method needs a non-null receiver. If the reference is null, the call throws a NullPointerException at run time. Construct the object with new before you call the method.
Key points
- Call form: object.method(arguments). The object before the dot is the receiver.
- The call uses that object's data; a different object is not updated.
- A void method does work but returns no value to assign.
- A non-void method returns a value you can store or print.
- Do not use ClassName.method for an instance method.
- A null receiver causes NullPointerException.
The call is sent to one object, so the other object is unchanged.