29

java之方法的参数传递(值传递和引用传递)

 4 years ago
source link: http://www.cnblogs.com/xiximayou/p/12040285.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

方法,必须有其所在类或对象调用时才有意义, 若方法有参数:

形参 :方法声明时的参数;

实参: 方法调用时实际传给形参的参数值;

java的实参如何传入方法呢?

首先要明确:变量分为两大类: 基础数据类型、引用数据类型

基础数据类型参数传递 方式只有一种: 值传递 。即将实际参数值的副本(复制品)传入方法内,而参数本身不受影响;

public class Test{
    
    public static void test(int i) {
        i = 6;
        System.out.println(i);
    }
    
    public static void main(String[] args) {
        int i = 2;
        test(i);
        System.out.println(i);
    }
}

输出:6 2

说明:也就是说test方法中的i和main方法中的i不是同一个i,它们在内存中的地址是不同的。总之,基本数据类型在传递参数的过程中,先将实参的值赋值到形参上,然后再在栈中开辟一个内存,将该值赋给新的变量。

引用数据类型参数传递 ,原来的实例化的对象和新建立的实例化对象都指向同一个对象,因此引用对象值的改变会影响到new出来的对象。

DataSwap.java

public class DataSwap {
    public int a;
}

Test.java

public class Test{
    
    public static void swap(DataSwap ds1) {
        ds1.a = 6;
        System.out.println(ds1.a);
    }
    
    public static void main(String[] args) {
        DataSwap ds = new DataSwap();
        System.out.println(ds.a);
        swap(ds);
        System.out.println(ds.a);
    }
    
}

输出:0 6 6

说明:对象在实例化ds时,成员变量a被赋予初始值0,然后将ds对象传给形参ds1,此时,ds和ds1虽然在栈内存中都有着各自的地址,但是它们都指向同一个对象DataSwap,然后通过ds1对象改变a的值,实际上是改变了DataSwap对象的值,因此也会影响到其它实例化的对象,因此最后输出为0 6 6。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK