Java - 方法调用后对象状态不会更改 [英] Java - Object state does not change after method call

查看:166
本文介绍了Java - 方法调用后对象状态不会更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初学java问题,但我无法理解下面的例子中如何使用call-by-Value(或Reference) -

Beginner java question, but I cannot understand how call-by-Value ( or Reference ) is working in the example below -

String值是怎么回事在我的自定义String对象退出方法后修改。 ?与Date等其他类相同。

How come the String value is not modified after it exits the method while my custom String Object is. ? Same with other classes like Date..

public class StringMadness {

public static void main(String[] args) {
    String s = "Native String";
    CustomStringObject cs = new CustomStringObject();
    System.out.println("Custom String Before: " + cs.str);
    hello(cs);
    System.out.println("Custom String After: " + cs.str);

    System.out.println("Native String Before: " + s);
    hello(s);
    System.out.println("Native String After: " + s);
}

private static void hello(String t) {
    t = "hello " + t;
}

private static void hello(CustomStringObject o) {
    o.str = "hello " + o.str;
  }
}

class CustomStringObject {

String str = "Custom String";
}


推荐答案

比较这两种方法:

private static void hello(String t) {
    t = "hello " + t;
}

private static void hello(CustomStringObject o) {
    o.str = "hello " + o.str;
}

在第一种情况下,您要为<$ c分配新值$ C> T 。这对调用代码没有影响 - 你只是改变一个参数的值,所有的参数都是用Java中的值传递的。

In the first case, you're assigning a new value to t. That will have no effect on the calling code - you're just changing the value of a parameter, and all arguments are passed by value in Java.

在第二种情况下,您要为 o.str 分配一个新值。这改变了 o 的值引用的对象中的字段的值。调用者看到该更改,因为调用者仍然具有对该对象的引用。

In the second case, you're assigning a new value to o.str. That's changing the value of a field within the object that the value of o refers to. The caller will see that change, because the caller still has a reference to that object.

简而言之:Java总是使用pass by value,但是你需要记住,对于类,变量(或实际上任何其他表达式)的值是引用,而不是对象。您不需要使用参数传递来查看:

In short: Java always uses pass by value, but you need to remember that for classes, the value of a variable (or indeed any other expression) is a reference, not an object. You don't need to use parameter passing to see this:

Foo foo1 = new Foo();
Foo foo2 = foo1;
foo1.someField = "changed";
System.out.println(foo2.someField) // "changed"

第二line这里将 foo1 的值复制到 foo2 - 这两个变量引用同一个对象,所以它不会你使用哪个变量来访问它。

The second line here copies the value of foo1 into foo2 - the two variables refer to the same object, so it doesn't matter which variable you use to access it.

这篇关于Java - 方法调用后对象状态不会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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