【问题标题】:Why static method cannot make values change unless I return the values [duplicate]为什么静态方法不能改变值,除非我返回值[重复]
【发布时间】:2015-10-01 04:32:14
【问题描述】:

我今天学习了静态方法,我对静态方法内部的值如何变化感到困惑。 当我写这样的静态方法时

public class test{
public static int printInt(int t,int n){
System.out.println(t);
t= t + n;
return n;
}
}

并在 main 中调用它

public class Method {
public static int i;
public static int m;
public static void main(String[] args){
    i = 5;
    m = 6;

    test.printInt(i,m);
    System.out.println(i);
}
}

t 不会像我想的那样改变。 如果静态方法只改变你返回的值?

【问题讨论】:

    标签: java static static-methods


    【解决方案1】:

    术语static 用最简单的术语表示属于该类的东西。上面代码中的方法printInt属于test类,而不是这个类的具体实例。

    在另一个类Method 中的主方法中,您尝试将局部变量im 作为参数传递,并且由于它们的副本将传递给方法printInt。您对副本而不是实际参数进行更改。所以更改不会反映在 main 方法中。

    注意:在 Java 中使用驼峰式和其他标准编码约定。将类命名为 Method 也是一个坏主意。

    【讨论】:

    • 那么我真的想让它反映在 main 方法中吗?谢谢!
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2016-09-20
    • 1970-01-01
    • 2017-09-28
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多