[英]Accesing variable from a different class in java
Is there a way i can pass a variable from one class with main to another one with main method. 有没有一种方法可以将变量从具有main的一个类传递给具有main方法的另一类。 For example
例如
class A
{
public static void main(String [] args)
{
int num = 5;
}
}
class B
{
public static void main(String []args)
{
}
}
Is there a way Class B can access int num from class A without getting null value? B类是否可以通过一种方法从A类访问int num而不获取空值?
num
is a variable with scope only in the main()
method. num
是仅在main()
方法中具有范围的变量。 It effectively disappears once the method finishes up. 方法完成后,它实际上会消失。 This is true even considering that
main()
is static. 即使考虑到
main()
是静态的,也是如此。
You can do this however: 您可以执行以下操作:
class A {
public int num = 5;
public static void main(String[] args) {
}
}
class B {
public static void main(String[] args) {
System.out.println(new A().num); // should print '5'
}
}
Notice that you need to create a new instance of A
in order to access num
, since num
is an element of the object A
. 注意,由于
num
是对象A
的元素,因此需要创建A
的新实例以访问num
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.