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
How to update a variable in one class from another class
提问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 AddSomething
class and addOne()
method
这是AddSomething
类和addOne()
方法
public class AddSomething{
public static void addOne(int a){
a++;
}
}
The addOne
method is not adding anything
该addOne
方法没有添加任何东西
System.out.println("Value of a is: "+String.valueOf(a));
// Prints 0 not 1
How can I make Add
class update variable a
in Main
class?
如何在课堂上制作Add
类更新变量?a
Main
采纳答案by Eran
addOne
receives a copy of a
, so it can't change the a
variable 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 AddSomething
class..
而在AddSomething
课堂上..
public class AddSomething
{
public static void addOne(){ Main.a++ };
}
AddSomething
must be in same package as Main
class, as int a
has default access modifier.
AddSomething
必须与Main
类在同一个包中,因为int a
具有默认访问修饰符。