Unit 1 · 12 min
1.14 Calling Instance Methods
Instance methods act on one particular object.
Summary, objectives and course and exam description (CED) codes
Instance methods are called on objects of the class, using the object's name and the dot operator, as in p.grow(5). They act on that one object. Calling a method on a null reference throws a NullPointerException.
By the end of this session you can
- 1.14.A Develop code to call instance methods and determine the result of these calls.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. Calling instance methods with the dot operator
Instance methods are called on objects of the class. The dot operator is used with the object name to call an instance method 1.14.A.1. The method acts on that one object.
This continues the topic 1.13 example: p refers to a Plant named "Fern" with height 30, and q refers to a Plant named "Mint" with height 0.
Plant p = new Plant("Fern", 30);
Plant q = new Plant("Mint");
p.grow(5); // void: a statement on its own
System.out.println(p.getHeight()); // 35
System.out.println(q.getName() + " " + q.getHeight()); // Mint 0
Output:
35
Mint 0
p.grow(5) changed only the object p refers to. q still has height 0.
An instance method needs an object, so calling it with the class name does not compile:
// does not compile
Plant.grow(5);
Real view:
error: non-static method grow(int) cannot be referenced from a static context
2. NullPointerException
A method call on a null reference results in a NullPointerException 1.14.A.2. The code compiles, but the program stops when the call runs.
Plant r = null; // r refers to no object
System.out.println("Checking r");
System.out.println(r.getHeight());
System.out.println("Done");
Output:
Checking r
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Plant.getHeight()" because "r" is null
Done is never printed: the exception interrupts the normal flow of the program (topic 1.1). The exact wording after the colon can differ between Java versions; the exception name is what matters.
Watch out: printing a null variable, as in System.out.println(r);, is fine and prints null. Only calling a method on it throws the exception.
3. Aliases: two names, one object
After Plant b = a;, both variables refer to the SAME object. Calling an instance method through either name changes that one object.
Plant a = new Plant("Basil", 10);
Plant b = a;
b.grow(5);
a.grow(3);
System.out.println(a.getHeight() + " " + b.getHeight());
Output:
18 18
10 + 5 + 3 is 18, and both names report it, because there is only one Plant. (Unit 3 studies aliasing in more depth.)
4. Looking ahead to Unit 3: inside a non-void method
Inside a class, a method’s statements can use the object’s attributes directly, and a return statement sends one value back to the caller and ends the method. The value must match the return type in the header. This is what the free-response practice for this unit asks you to write.
public class Plant
{
private String name;
private int height;
public Plant(String n, int h)
{
name = n;
height = h;
}
// inside the Plant class
public String getInitial()
{
return name.substring(0, 1);
}
}
// in main
Plant p = new Plant("Fern", 30);
String first = p.getInitial();
System.out.println(first);
Output:
F
If p refers to a Plant named "Fern", p.getInitial() returns "F". A method returns a value; it does not print it. The caller decides what to do with the value.
Lock it in: memory hooks
- Instance method callobject dot method: tell one particular object what to do.
- nullYou cannot ask nobody to do something: a call on null throws a NullPointerException.
Common misconceptions
"You can call an instance method with the class name, like Plant.grow(5)."
Not quite. An instance method needs an object. Plant.grow(5) does not compile; p.grow(5) works, where p refers to a Plant object.
"Calling a method on null returns null or 0."
Not quite. It throws a NullPointerException at run time and the program stops. The code compiles, because the compiler does not know the variable will be null.
"After Plant b = a; there are two plants."
Not quite. There is one Plant object and two references to it. A change made through b is seen through a.
Exam traps
- Aliasing: after Plant b = a; both variables refer to the SAME object, so b.grow(5) changes what a.getHeight() returns too.
- Printing a null variable prints null, but calling a method on it throws a NullPointerException.
- A void instance method, such as grow, is a statement on its own; a non-void one, such as getHeight, gives a value to store or use.
2PracticeRecall it, then check yourself
In 30 seconds
- Instance methods are called on objects of the class.
- Use the object's name and the dot operator: p.grow(5).
- Plant.grow(5) does not compile, because an instance method needs an object.
- A method call on a null reference throws a NullPointerException.
- Aliases (two variables referring to the same object) see the same changes.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 4 questions
Checkpoint: Calling Instance Methods
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
-
Plant class (implementations not shown) Constructor or method What it does public Plant(String n) Sets the name to n and the height to 0 public Plant(String n, int h) Sets the name to n and the height to h public String getName() Returns the name public int getHeight() Returns the height public void grow(int cm) Adds cm to the height -
Plant class (implementations not shown) Constructor or method What it does public Plant(String n) Sets the name to n and the height to 0 public Plant(String n, int h) Sets the name to n and the height to h public String getName() Returns the name public int getHeight() Returns the height public void grow(int cm) Adds cm to the height -
Plant class (implementations not shown) Constructor or method What it does public Plant(String n) Sets the name to n and the height to 0 public Plant(String n, int h) Sets the name to n and the height to h public String getName() Returns the name public int getHeight() Returns the height public void grow(int cm) Adds cm to the height -
Plant class (implementations not shown) Constructor or method What it does public Plant(String n) Sets the name to n and the height to 0 public Plant(String n, int h) Sets the name to n and the height to h public String getName() Returns the name public int getHeight() Returns the height public void grow(int cm) Adds cm to the height
3PrevailLock it in for exam day
By the numbers
- Parts of an instance method call three parts CED 1.14.A.1
- the object referencevariable name
- the dot operator
- the method name with its arguments
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Instance methodtap to flip
A method called on an object of the class, using the object's name and the dot operator.
Example and CED codes -
Dot operatortap to flip
The . used to call a method on an object (p.grow(5)) or a class method with the class name (Math.abs(-3)).
Example and CED codes -
NullPointerExceptiontap to flip
The exception thrown when a method is called on a null reference.
Example and CED codes -
nulltap to flip
A special literal meaning a reference variable is not associated with any object.
Example and CED codes -
Object referencetap to flip
The value a reference variable holds: it can be thought of as the memory address of the object.
Example and CED codes
Questions students ask
What is an instance method in Java?
An instance method is a method called on an object of the class. It works with that object's attributes. You call it with the object's name and the dot operator, such as p.getHeight().
What is the difference between an instance method and a class method?
An instance method is called on an object (p.grow(5)) and has no static keyword. A class method has static in its header and is called with the class name (Math.sqrt(9.0)).
What causes a NullPointerException?
Calling a method on a reference variable that holds null. There is no object to run the method on, so the program throws a NullPointerException at run time.