Task 7 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 — passing objects to methods

Lesson

Что метод может изменить, а что нет

Java always passes a copy. For a number that means the method works on its own copy, and the original is untouched. For an object the reference is copied — and a copy of the address still leads to the same object. So the method can change the object's fields, and the caller sees it.


Worked example

static void bump(int n) { n = n + 100; }        // original unchanged
static void rename(Dog d) { d.name = "changed"; } // field DOES change
static void replace(Dog d) { d = new Dog("new"); } // caller sees nothing

Compare the last two. rename reaches through the reference and edits the object — visible outside. replace points the local copy at a different object — the caller's variable still points at the old one.

Rule of thumb: a method can change what the object contains, but cannot change which object the caller's variable points at.


▶ Try it: run this, then change something and run it again.



A method changes a field of an object it was given. The caller...


A method assigns a brand-new object to its parameter. The caller...


Type exactly what this program prints.

class Dog {
    String name;

    Dog(String name) {
        this.name = name;
    }
}

public class Main {

    static void rename(Dog d) {
        d.name = "Bo";
    }

    public static void main(String[] a){
        Dog d = new Dog("Rex");
        rename(d);
        System.out.println(d.name);
    }
}

Why is a number unchanged but an object field changed?


True or false?