Task 5 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.3 Instance methods — a method that changes a field

Lesson

Methods can change the object

An instance method can also change the object's fields, not just read them. This lets an object update its own state — for example, a bank account that grows when you deposit into it. Calling the method on one object changes only that object.


Worked example

class Account {
    int balance;

    void deposit(int amount) {
        balance = balance + amount;   // changes the field
    }
}

Account a = new Account();
a.balance = 100;
a.deposit(50);
System.out.println(a.balance);   // 150

▶ Try it: deposit(amount) adds to the object's balance. Run this, then change the starting balance or the deposit amount and re-run.



deposit(int amount) does balance = balance + amount. After balance = 100 and a.deposit(50), what is a.balance?


A method increment() does count = count + 1. The count field starts at 0. Type its value after calling increment() three times:


Sort each method by whether it reads a field or changes a field.


True or false?