AP® Computer Science A · Unit 1 · Topic 1.14
Calling Instance Methods
Calling an instance method means picking an object with the dot operator and asking that specific object to run its code on its own data. Each object's fields stay separate, so a method call on one object never touches another.
An instance method belongs to a class, but it only runs on a particular object. That's why you write r1.getArea() instead of just getArea() — the dot operator tells Java which object's data to plug in. A class method, marked static, belongs to the class itself and needs no object out front because it isn't reading any object's fields. An instance method almost always reads or changes fields, so it needs an object to read or change.
When you call r1.getArea(), Java looks at r1's own width and height, multiplies them, and hands back the result. Call the same method on r2, and Java uses r2's width and height instead — same code, different data, because each object carries its own copy of every instance variable. If r1 has width 4 and height 5, r1.getArea() returns 20. If r2 has width 3 and height 7, r2.getArea() returns 21, even though both calls run the exact same line of code inside Rectangle.
A void method works the same way, it just changes the object's fields instead of handing back a value. Calling c1.increment() finds c1's count field and adds one to it, then returns nothing — the change lives inside c1. This is also why calling a method on one object can never leak over into another: c2 has its own count field sitting at its own address on the heap, completely separate from c1's. Nothing you do to c1 can reach it.
Key terms
- instance method
- A method that operates on a specific object's fields, called with objectName.methodName().
- dot operator
- The symbol that connects an object to the method or field it is calling or accessing.
- instance variable
- A field each object keeps its own separate copy of, holding that object's particular data.
- void method
- A method that performs an action or changes data but returns no value.
Watch it explained
- How it worksHow does the dot operator send a message to one specific object and its own data?
- Worked exampleTrace what two Rectangle objects with different widths return from the same getArea call.
- How it worksHow does a void instance method change an object without returning anything at all?
- Common mistakeWhy doesn't calling a method on one object affect any of the other objects?
Check yourself
End of topic.