如果传入方法,最终变量如何工作? [英] How final variable works if passed in a method?

查看:78
本文介绍了如果传入方法,最终变量如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,只是想了解更多有关final方法参数的信息.

I have a very simple question and just asking to know more about final method arguments.

final变量只能在其生命周期内初始化一次.在JAVA方法中,参数接受为按值传递,引用也作为值传递.

final variables can be initialized just once in its life. In JAVA method arguments are accepted as pass by value and reference is also passed as a value.

现在我的问题是:

这是示例代码:

public static void xyz(Abc obj) {
    System.out.println("hash code in xyz method :"+obj.hashCode());
    obj = new Abc(); // here there is no issue to initialize it again
}

public static void abc() {
    final Abc obj = new Abc();
    //obj=new Abc(); // final variable can be initialized just once

    System.out.println("hash code in abc method :"+obj.hashCode());
    xyz(obj);
}

public static void main(String[] a) {
    abc();
}

推荐答案

abc中的obj变量与xyz中的obj参数不同.调用xyz时,xyz使用引用的副本(注意:这不是对象的副本,而是对象的副本,但这是引用的副本).因此,当在xyz中执行obj = new Abc()时,它仅修改xyz中的副本.它对abc()中的obj没有影响,因为引用是通过值传递的.

The obj variable in abc is not the same as the obj parameter in xyz. When you call xyz, xyz works with a copy of the reference (NOTE: this is not a copy of the object, but it's a copy of the reference). So when obj = new Abc() is executed in xyz, it modifies only the copy in xyz. It has no effect on the obj in abc(), because the reference is passed by value.

这篇关于如果传入方法,最终变量如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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