【问题标题】:passing a variable into a private method gives you scope to that variable correct? [duplicate]将变量传递给私有方法可以为您提供该变量的范围对吗? [复制]
【发布时间】:2016-02-01 02:54:49
【问题描述】:

所以在下面的代码中,如果 exampleVar 在第一次打印出来时为零,然后再次打印出来,会是两个吗?我试图不使用全局变量,除此之外,我想不出其他方法。

public int method ... {
        int exampleVar = 0;
        System.out.println(exampleVar); // would be zero
        pmethod(exampleVar,);
        System.out.println(exampleVar); // would be two?
        }

        private int pmethod(int exampleVar) {
            exampleVar++;
            if(exampleVar != 2){
               pmethod(exampleVar);
            }
        }

人们说这个答案是无效的,因为这个答案虽然正确但太吵了。使用完全抽象且令人困惑的 foo 示例。作为一个 Java 新手,我拒绝了这个问题,因为它不是一个清晰明确的答案。

【问题讨论】:

    标签: java variables scope


    【解决方案1】:

    您的第二个语句将打印“0”,因为“exampleVar”具有第一个方法的本地范围。

    【讨论】:

    • 所以我将exampleVar传递给私有方法并添加到它,不会改变公共方法中exampleVar的值吗?
    • 即使该方法是“公共”的,它也不会改变它在第一个“公共”方法中的值,因为这是第一个方法的局部变量。要从第二种方法获取值,您可以在第一种方法中返回值并分配给“exampleVar”。基本上,您不会共享变量,除非它是全局变量。
    • 我明白了,所以我必须修改代码,以便在某些时候我们看到示例 var = pmethod(...) 在 pmethod 中带有 return 语句
    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 2017-05-21
    • 2023-02-03
    • 2013-07-31
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多