How to pass a Java object as a parameter

There are two ways to pass objects as parameters in Java: pass by value and pass by reference.

  1. Pass-by-Value: When passing an object as a parameter, what is actually passed is the reference (address) of the object, not the object itself. Inside the method, the parameter receives a copy of the object’s reference, meaning the parameter and the argument both point to the same object. If the object’s properties are modified inside the method, it will actually change the same object, affecting the object outside of the method.

Sample code:

public class Main {
    public static void main(String[] args) {
        Person person = new Person("Alice");
        changeName(person);
        System.out.println(person.getName()); // 输出 "Bob"
    }
    
    public static void changeName(Person p) {
        p.setName("Bob");
    }
}

class Person {
    private String name;
    
    public Person(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}
  1. Pass-by-reference: In Java, objects are passed by value, but the reference to the object can be modified to achieve passing by reference. This can be done by defining a container (such as an array or collection) that holds the object reference.

Sample code:

public class Main {
    public static void main(String[] args) {
        Person[] persons = new Person[1];
        persons[0] = new Person("Alice");
        changeName(persons);
        System.out.println(persons[0].getName()); // 输出 "Bob"
    }
    
    public static void changeName(Person[] p) {
        p[0].setName("Bob");
    }
}

class Person {
    private String name;
    
    public Person(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}

Through the aforementioned two methods, objects in Java can be passed as parameters and can be modified within a method.

广告
Closing in 10 seconds
bannerAds