Java是值传递还是引用传递

1.  我们知道在程序设计语言中,将参数传递分为按值调用和按引用调用。

   按值调用:表示方法接收的是调用者提供的值。而按引用调用表示方法接收的是调用者提供的变量地址。
   一个方法可以修改传递引用所对应的变量值,而不能修改传递值调用所对应的变量值。

   我们在c++中知道判断最好的方法就是写一个swap函数,根据结果看就能判断是按值调用还是按引用调用。

class Student {
    private float score;
}

public class ParamTest {
    public static void main(String[] args) {
        Student x = new Student(0);
        Student y = new Student(100);

        System.out.println("交换前:");
        System.out.println("x的分数:" + x.getScore() + "--- y的分数:" + y.getScore());

        swap(x, y);

        System.out.println("交换后:");
        System.out.println("x的分数:" + x.getScore() + "--- y的分数:" + y.getScore());
    }

    public static void swap(Student a, Student b) {
        Student temp = a;
        a= b;
        b= temp;
    }
}

   运行结果:

交换前:
a的分数:0.0--- b的分数:100.0
交换后:
a的分数:0.0--- b的分数:100.0

   可以看出,两者并没有实现交换。从这个过程中可以看出,Java对对象采用的不是引用调用,实际上,对象引用进行的是值传递。

2.  要想实现数值变换,我们可以写函数来实现:

class Student {

    private float score;

    public Student(float score) {
        this.score = score;
    }

    public void setScore(float score) {
        this.score = score;
    }

    public float getScore() {
        return score;
    }


}

public class ParamTest {
    public static void main(String[] args) {
        Student stu = new Student(80);
        raiseScore(stu);
        System.out.print(stu.getScore());
    }

    public static void raiseScore(Student s) {
        s.setScore(s.getScore() + 10);
    }
}

3.  总结一下Java总是采用按值调用。方法得到的是所有参数值的一个拷贝,特别的,方法不能修改传递给它的任何参数变量的内容。方法参数共有两种类型:基本数据类型和对象引用

posted @ 2019-04-18 11:08  从让帝到the_rang  阅读(190)  评论(0编辑  收藏  举报