java 如何从另一个类更新一个类中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33952228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:20:28  来源:igfitidea点击:

How to update a variable in one class from another class

java

提问by the_prole

I realize this is probably a really basic question, but I can't figure it out.

我意识到这可能是一个非常基本的问题,但我无法弄清楚。

Say I have this main class

说我有这个主课

public class Main{

    public static void main(String[] args){
        int a = 0;
        AddSomething.addOne(a);
        System.out.println("Value of a is: "+String.valueOf(a));
    }
}

Here is AddSomethingclass and addOne()method

这是AddSomething类和addOne()方法

public class AddSomething{

    public static void addOne(int a){

        a++;

    }
}

The addOnemethod is not adding anything

addOne方法没有添加任何东西

System.out.println("Value of a is: "+String.valueOf(a));
// Prints 0 not 1

How can I make Addclass update variable ain Mainclass?

如何在课堂上制作Add类更新变量?aMain

采纳答案by Eran

addOnereceives a copy of a, so it can't change the avariable of your main method.

addOne接收 的副本a,因此它无法更改a您的 main 方法的变量。

The only way to change that variable is to return a value from the method and assign it back to a:

更改该变量的唯一方法是从该方法返回一个值并将其分配回a

a = Add.addOne(a);

...

public int addOne(int a){
    return ++a;
}

回答by midikko

Thats becouse primitive types in java pass to methods by value. Only one way to do what you want is reassign variable, like :

那是因为 java 中的原始类型按值传递给方法。只有一种方法可以做你想做的事是重新分配变量,比如:

public class Main{

    public static void main(String[] args){
        int a = 0;
        a = Add.addOne(a);
        System.out.println("Value of a is: "+String.valueOf(a));
    }
}

and

public class AddSomething{

    public static int addOne(int a){

    return a++;

    }
}

回答by Akoder

I know, Eran's answer is what you all need. But just to show another way, posting this answer.

我知道,Eran 的回答正是你们所需要的。但只是为了展示另一种方式,发布这个答案。

public class Main
{
  static int a = 0;
  public static void main(String[] args)
  {
    AddSomething.addOne();
    System.out.println("Value of a is: "+a);
  }
}

And in AddSomethingclass..

而在AddSomething课堂上..

public class AddSomething
{
    public static void addOne(){ Main.a++ };
}

AddSomethingmust be in same package as Mainclass, as int ahas default access modifier.

AddSomething必须与Main类在同一个包中,因为int a具有默认访问修饰符。