Passing objects to methods

When passing objects to methods, only the reference is copied, not the object itself. If the method has access to attributes of the object, it can change the object. This change is preserved after the method returns.

Example

This is a Java program that defines two classes, Person and PassingObjects.

The Person class is a simple class that has a single field called name.

The PassingObjects class contains a static method setName that takes two parameters: a string n and an object of type Person called o. The method sets the value of the name field of the Person object to the value of n.

In the main method of the PassingObjects class, two instances of the Person class are created and stored in the variables p1 and p2. The setName method is then called twice, once for each of the Person objects, with the values "John" and "Tom" for the n parameter, and the references to p1 and p2 for the o parameter.

class Person {
    String name;
}

public class PassingObjects {
    static void setName(String n, Person o) {
        o.name = n;
    }
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();

        setName("John", p1);
        setName("Tom", p2);
        System.out.println(p1.name);
        System.out.println(p2.name);
    }
}
Output
John
Tom