Unit 1.14: Instance Methods
Instance Methods
- Definition: Instance methods define the behaviors of an object. Unlike static methods, they must be called on a specific instance (object) of a class.
Object Behavior
- Instance methods define what an object can do. They have access to the object's instance variables and can modify the object's state.
- Syntax: Use the dot operator (
.) to call a method on an object reference.objectVariable.methodName(arguments);
NullPointerException
As introduced in Unit 1.13 (The null Reference), assigning null to a variable is valid, but using it carelessly leads to errors.
Dereferencing null
- A
NullPointerExceptionoccurs when you attempt to access a method or attribute using a reference that points tonull. It is one of the most common runtime errors in Java.
- Recap: A
NullPointerExceptionis a runtime error that stops your program. - The Cause: This exception happens specifically when you try to use the dot operator (
.) on a reference that points to nothing. You are asking "nobody" to do "something," which is impossible.
| Concept | Explanation | Example |
|---|---|---|
| Valid Call | Calling a method on an initialized object. | s.length() |
| Invalid Call | Calling a method on a null variable. |
nullStr.length() -> Error |
Examples
Calling Methods
This program demonstrates how to call an instance method (length()) on a String object.
Task: Invoking an instance method on a String object.
public class MethodExample {
public static void main(String[] args) {
String s = "AP Computer Science";
// .length() is an instance method called on the object 's'
int len = s.length();
System.out.println("The string is: " + s);
System.out.println("The length of the string is: " + len);
}
}
Causing an Exception (NullPointerException)
This program demonstrates what happens when you try to call a method on a variable that is null. It will compile successfully, but it will crash when run.
Task: Triggering a NullPointerException by calling a method on a null reference.
public class NullExample {
public static void main(String[] args) {
// emptyRef is declared but points to no object
String emptyRef = null;
System.out.println("Attempting to call .length() on a null reference...");
// This line causes a NullPointerException because there
// is no object to perform the action on.
int x = emptyRef.length();
// This line will NEVER be reached because the program crashes above.
System.out.println("The length is: " + x);
}
}