欢迎访问宙启技术站
智能推送

Java中函数的参数传递方法详解

发布时间:2023-06-04 12:32:52

Java 中函数的参数传递方法包括传值和传引用两种方法。相信任何一位 Java 开发者都会使用这两种方法,因此本篇文章将会深入了解这两种方法的运作原理和适用情况,希望可以帮助大家更好地掌握这两种方法。

1. 传值

Java 是一种采用传值的语言,所以当我们调用一个函数时,函数的参数都会被复制一份,然后被传递到函数中。这意味着,如果在函数中修改了参数的值,就不会对原始值产生影响。以下是一个简单的示例:

public static void changeValue(int value) {
    value = 10;
    System.out.println("value in function is: " + value);
}

public static void main(String[] args) {
    int value = 5;
    System.out.println("value before function is called: " + value);
    changeValue(value);
    System.out.println("value after function is called: " + value);
}

输出结果为:

value before function is called: 5
value in function is: 10
value after function is called: 5

正如我们所看到的那样,当我们在函数中将值改为 10 时,原始值仍然为 5。这就是 Java 中传值方法的工作原理。

2. 传引用

除了传值方法之外,Java 还支持传引用方法。当我们传递一个对象时,对象的地址会被复制一份并传递到函数中,这意味着如果我们在函数中修改了对象的值,那么对原始对象也会造成影响。

以下是一个简单的示例:

public static void changeName(Student student) {
    student.setName("Jack");
    System.out.println("name in function is: " + student.getName());
}

public static void main(String[] args) {
    Student student = new Student("Tom");
    System.out.println("name before function is called: " + student.getName());
    changeName(student);
    System.out.println("name after function is called: " + student.getName());
}

输出结果为:

name before function is called: Tom
name in function is: Jack
name after function is called: Jack

正如我们所看到的那样,当我们在函数中将名字改为 Jack 时,原始对象的名字也被改变了。这就是传引用方法的工作原理。

需要注意的是,在传引用方法中,我们要小心使用。如果我们在函数中不小心改变了对象地址,那么原始对象就无法被访问了。以下是一个简单的示例:

public static void changeAddress(Student student) {
    student = new Student("Bob");
    System.out.println("address in function is: " + student);
}

public static void main(String[] args) {
    Student student = new Student("Tom");
    System.out.println("address before function is called: " + student);
    changeAddress(student);
    System.out.println("address after function is called: " + student);
}

输出结果为:

address before function is called: Student@5ebec15
address in function is: Student@1c20c684
address after function is called: Student@5ebec15

正如我们所看到的那样,当我们在函数中为对象创建了一个新的地址时,原始对象的地址没有被改变,因此我们应该小心使用传引用方法。

总结:

Java 中函数的参数传递方法包括传值和传引用两种方法。在传值方法中,函数的参数会被复制一份,不会对原始值产生影响;在传引用方法中,函数的参数地址会被复制一份,如果我们在函数中修改了对象的值,对原始对象也会造成影响。所以,我们在使用这两种方法时需要根据具体情况选择合适的方法。