Java——在类之间传递变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18194661/
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
Java -- Pass variable from class to class
提问by user2676140
I know that to pass from within the Sameclass, I would do something like this --- but what about between classes?
我知道要从同一个班级内部传递,我会做这样的事情——但是在班级之间呢?
class TestMe{
public static void main(String[] args)
{
int numberAlpha = 232;
TestMe sendNumber = new TestMe();
sendNumber.Multiply(numberAlpha);
}
void Multiply(int var)
{
var+=40;
}
}
采纳答案by Xabster
You use getters and setters.
您使用 getter 和 setter。
class A {
private int a_number;
public int getNumber() { return a_number; }
}
class B {
private int b_number;
public void setNumber(int num) { b_number = num; }
}
.. And in your main method, wherever it is:
.. 在你的主要方法中,无论在哪里:
public static void main(String[] args) {
A a = new A();
int blah = a.getNumber();
B b = new B();
b.setNumber(blah);
}
You can also use constructors as a means of an "initial setter" so that the object is always created with a minimum set of variables already instantiated, for example:
您还可以使用构造函数作为“初始设置器”的一种方式,以便始终使用已实例化的最小变量集创建对象,例如:
class A {
private int a_number;
public A(int number) { // this is the only constructor, you must use it, and you must give it an int when you do
a_number = number;
}
public int getNumber() { return a_number; }
}