为什么java同时使用值传递和引用传递? [英] Why does java use both pass-by-value and pass-by-reference?

查看:48
本文介绍了为什么java同时使用值传递和引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java 是pass-by-reference"吗?

也许我遗漏了一些东西……但我真的不明白为什么 Java 同时使用值传递和引用传递.为什么不只使用一种范式?

Maybe I'm missing something...but I can't really understand why Java uses both the pass-by-value and pass-by-reference. Why not using only one paradigm?

推荐答案

没有.Java 纯粹是按值传递的.处理对象时传递的值是对象引用,但这与通过引用传递"无关.

It doesn't. Java is purely pass-by-value. The value passed when you're dealing with an object is an object reference, but that has nothing to do with "pass by reference."

通过引用传递意味着可以向函数传递一个变量并在调用函数中更改该变量的内容.这在 Java 中不存在.

Pass-by-reference means that a function can be passed a variable and change the contents of that variable in the calling function. That does not exist in Java.

例如:

void foo() {
    int a;

    a = 42;
    bar(a);
    System.out.println(a); // Will ALWAYS be 42
}

void bar(int b) {
    b = 67;
}

对比 C++,它确实有传递引用:

Contrast with C++, which does have pass-by-reference:

// C++ code
void foo() {
    int a;

    a = 42;
    bar(a);
    cout << a; // 67?!
}
void bar(int& a) { // <== Note the &
    a = 67;
}

Java 没有 C++ 中的 &(或 C# 中的 out/ref).

Java has no equivalent of the & in C++ (or out / ref in C#).

您可能正在考虑对象引用,它是引用"一词的完全不同用法,而不是引用"在传递引用中的用法.让我们看一个对象的例子:

You're probably thinking of object references, which is a completely separate use of the word "reference" than the "reference" in pass-by-reference. Let's look at an example with objects:

void foo() {
    Object o1, o2;

    o1 = new Object();
    o2 = o1;
    bar(o1);
    System.out.println(o1 == o2); // Will ALWAYS be true
}

void bar(Object o) {
    o = new Object();
}

如果 Java 有传递引用(并且我们使用它来将对象变量传递给 bar),foo<中的 ==/code> 将是错误的.但事实并非如此,也没有办法做到这一点.

If Java had pass-by-reference (and we'd used it to pass the object variable to bar), the == in foo would be false. But it isn't, and there is no way to make it so.

对象引用允许您更改传递给函数的对象的状态,但您不能更改调用函数中包含它的变量.

The object reference allows you to change the state of the object passed into the function, but you cannot change the variable that contained it in the calling function.

这篇关于为什么java同时使用值传递和引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆