Java - 将变量从类传递给类 [英] Java -- Pass variable from class to class
本文介绍了Java - 将变量从类传递给类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道要从相同类中传递,我会做这样的事情 - 但是类之间怎么样?
I know that to pass from within the Same class, 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;
}
}
推荐答案
你使用getter和setter。
You use getters and setters.
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; }
}
这篇关于Java - 将变量从类传递给类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文