Java通过引用传递

编程入门 行业动态 更新时间:2024-10-28 18:30:34
本文介绍了Java通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这两个代码有什么区别:

What is the difference between this 2 codes:

代码A:

Foo myFoo; myFoo = createfoo();

其中

public Foo createFoo() { Foo foo = new Foo(); return foo; }

Vs。代码B:

Foo myFoo; createFoo(myFoo); public void createFoo(Foo foo) { Foo f = new Foo(); foo = f; }

这2个代码之间是否有任何差异?

Are there any differences between these 2 pieces of codes?

推荐答案

Java总是按值而不是通过引用传递参数。

Java always passes arguments by value NOT by reference.

让我通过示例解释一下:

public class Main { public static void main(String[] args) { Foo f = new Foo("f"); changeReference(f); // It won't change the reference! modifyReference(f); // It will modify the object that the reference variable "f" refers to! } public static void changeReference(Foo a) { Foo b = new Foo("b"); a = b; } public static void modifyReference(Foo c) { c.setAttribute("c"); } }

我将分步说明:

  • 声明类型为 Foo的名为 f 的引用并将其分配给类型为 Foo 的新对象,其属性为f。

  • Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f". Foo f = new Foo("f");

    从方法方面,类型为 Foo 的引用声明名称 a ,并且它最初被分配给 null 。

    From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.

    public static void changeReference(Foo a)

    当你调用方法 changeReference ,引用 a 将被分配给作为参数传递的对象。

    As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.

    changeReference(f);

    声明类型为<$ c的名为 b 的引用$ c> Foo 并将其分配给类型为 Foo 的新对象,其属性为b。

    Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".

    Foo b = new Foo("b");

    a = b 正在重新分配参考 a NOT f 到属性为b的对象。

    a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".

    当您调用 modifyReference(Foo c)方法时,a引用 c 已创建并分配给属性为f的对象。

    As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".

    c.setAttribute(c); 将更改引用 c 点的对象的属性对它来说,引用 f 指向它是同一个对象。

    c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.

    我希望您现在了解如何将对象作为参数传递在Java中:)

    I hope you understand now how passing objects as arguments works in Java :)

  • 更多推荐

    Java通过引用传递

    本文发布于:2023-06-10 22:49:08,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/620740.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:Java

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!