Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- Instance methods are called on objects of the class. The dot operator is used along with the object name:
box.area(). - A class method is called with the class name and needs no object; an instance method needs an object and cannot be called with just the class name.
- Each object has its own attribute values, so one method can give different results for different objects.
- A void method is called as a statement and can change the object. A non-void method returns a value to store or use in an expression.
- Arguments must match parameters in number, order and compatible type, and are passed by value.
- A method call on a
nullreference results in aNullPointerException: a run-time error. Stringmethods such aslength()andindexOf(...)are instance methods called onStringobjects.
Key relationships
| Call | Kind | Example |
|---|---|---|
Math.sqrt(16) |
class method | called through the class name |
small.area() |
instance method, non-void | an expression with the returned value |
small.grow(1); |
instance method, void | a statement that changes small |
word.length() |
instance method of String |
on a String object |
Rectangle.area() |
error | instance method called through a class name |
t.area() with t == null |
run-time error | NullPointerException |
| Situation | Result |
|---|---|
Rectangle s = r; then s.grow(4); |
r sees the change: same object |
| two separate objects | each keeps its own values |
int c = r.grow(2); |
compile-time error: void |
r.grow("2"); |
compile-time error: wrong argument type |
Assumptions and conventions
- The object name before the dot is a reference variable that must refer to an object when the call runs.
- Exceptions interrupt the normal flow: nothing after the failing call runs (Topic 1.1).
- The compiler checks that the method exists for the variable’s class, not that the variable is non-null.
- No calculator is allowed on the exam; trace the objects with a table.
Mistakes to avoid
- Calling an instance method with the class name.
- Forgetting that a void method changes the object but returns nothing.
- Assuming a call on one object changes all objects of the class.
- Missing that two names can refer to one object.
- Expecting a compile error for a
nullcall. - Storing the result of a void method.
- Passing the wrong number, order or type of arguments.
Quick self-check
- How do you call
areaon aRectanglenamedr? (r.area()) - Does
r.grow(2);return a value? (No: it is a void method that changesr.) - If
sandrrefer to the same object ands.grow(1);is called, what doesr.area()see? (The changed object.) - What happens when
t.area()runs andtisnull? (ANullPointerException.) - What does
"banana".length()return? (6)
Next: practice questions.