[英]How do you transfer a variable defined in the main method of one class to another?
I have seen this done in many programs but I cant seem to follow the programming logic. 我已经在许多程序中看到了这一点,但是我似乎无法遵循编程逻辑。
Lets say you have a simple class, ClassB. 可以说您有一个简单的类ClassB。 And in ClassB's main method you define an integer variable:
然后在ClassB的main方法中定义一个整数变量:
public class B {
public static void main(String[] args) {
int stuff = 333;
}
}
How can you transfer the variable to a different class, say ClassA, to be used. 如何将变量转移到要使用的其他类(例如ClassA)上。
public class A {
public static void main(String[] args) {
System.out.println(stuff);
}
}
Can someone please explain this to me in simple terms. 有人可以简单地向我解释一下。 I've been trying to learn this for 2 hours and cant wrap my head around it.
我一直在努力学习2个小时,无法绕过它。
You shouldn't have 2 main
methods. 您不应该有2种
main
方法。 Only one class
should (typically): 只有一个
class
(通常)应该:
ClassA.java ClassA.java
public class A {
public static void main(String[] args) {
ClassB b = new ClassB();
System.out.println(b.stuff);
}
}
ClassB.java ClassB.java
public class B {
public int stuff = 333; // member variable
}
You instantiate the second class
in the first one, then you're granted access to its public member variables . 您在第一个
class
中实例化第二个class
,然后被授予访问其公共成员变量的权限。
public static void main(String[] args)
is meant to be used as a starting point for a Java program. public static void main(String[] args)
旨在用作Java程序的起点。 Probably it's better to rename one of your methods to something else. 最好将其中一种方法重命名为其他方法。
The problem you are seeing, is that the scope of the variable int stuff
is limited to the main()
method of class B
, because it is declared within the body of the main()
method. 您看到的问题是,
int stuff
变量的范围仅限于B
类的main()
方法,因为它是在main()
方法的主体内声明的。 In order to make it visible, you need to declare it as a public field (which can be static in your case). 为了使其可见,您需要将其声明为公共字段(在您的情况下可以是静态的)。
I propose you change your program like follows: 我建议您按以下方式更改程序:
public class A {
public static int stuff;
public static void initStaticMembers() {
stuff = 333;
}
}
public class B {
public static void main(String[] args) {
A.initStaticMembers();
System.out.println(A.stuff);
}
}
I renamed the main()
method of A
to initStaticMembers()
and dropped the method parameters, since they are not needed in our case. 我改名
main()
方法A
到initStaticMembers()
和丢弃的方法参数,因为在我们的情况下是不需要的。 In order to use the field A.stuff
in B
, the method A.initStaticMembers()
needs to be called first. 为了使用
B
的字段A.stuff
,首先需要调用方法A.initStaticMembers()
。
Of course there are ways to improve this program, but I think you should learn Java one step at a time. 当然,有一些方法可以改进此程序,但是我认为您应该一次学习Java。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.