Java 通过引用传递

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

这两个代码有什么区别:

What is the difference between this 2 codes:

代码 A:

Foo myFoo; myFoo = createfoo();

哪里

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

对比.代码 B:

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

这两段代码有什么区别吗?

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"); } }

我将分步解释:

  • 声明一个名为 f 的类型为 Foo 的引用,并将其分配给一个类型为 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");

    在方法方面,声明了一个名为 a 的 Foo 类型的引用,并且它最初被分配给 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);

    声明一个名为 b 的类型为 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 而不是 f 重新分配给其属性为 的对象"b".

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

    当您调用 modifyReference(Foo c) 方法时,会创建一个引用 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 指向它的对象的属性,并且引用 c 的对象是同一个对象code>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:23,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/620745.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:Java

    发布评论

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

    >www.elefans.com

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