Unit 1.14
Calling Instance Methods
AP Computer Science A
Using Objects and Methods
Learning Objectives
By the end of this lesson, you will be able to:
- Understand what instance methods are and how they work
- Use the dot operator to call instance methods on objects
- Develop code that calls instance methods correctly
- Determine the results of method calls
- Recognize and avoid NullPointerException errors
What Are Instance Methods?
Instance methods are actions or behaviors that objects can perform.
- Instance methods belong to a specific object of a class
- They are called ON objects, not on the class itself
- Each object has access to the instance methods defined in its class
Real-World Analogy:
Think of a car object. Instance methods would be actions like:
- startEngine()
- accelerate()
- brake()
Each individual car can perform these actions.
The Dot Operator
To call an instance method, we use the dot operator (.)
Syntax:
Components:
- objectName - the specific object you're working with
- . - the dot operator (connects object to method)
- methodName - the name of the method to call
- (parameters) - any values the method needs
String Method Examples
Let's look at calling instance methods on String objects:
Each method is called ON the greeting object using the dot operator.
Methods with Parameters
Many instance methods require parameters (inputs):
Important: You must provide the correct number and type of parameters!
Methods that Return Values
Instance methods can return a value that you can use:
NullPointerException
CRITICAL CONCEPT
A method call on a null reference will result in a NullPointerException.
What is null?
null means the variable doesn't reference any object.
Why? You can't call a method on something that doesn't exist!
Avoiding NullPointerException
Check for null before calling methods:
Best Practice: Always consider whether an object might be null before calling methods on it.
Summary
Key Takeaways:
- Instance methods are called on objects of a class
- Use the dot operator (.) to call instance methods
- Syntax: objectName.methodName(parameters)
- Methods can take parameters and return values
- Calling a method on null causes a NullPointerException
- Always check for null when necessary
Remember for the AP Exam:
You must be able to determine the result of method calls and write code that correctly calls instance methods on objects.