[英]How can I use public constants in other classes?
I'm trying to access a public constant variable outside my class and I don't understand why isn't working.我正在尝试访问班级之外的公共常量变量,但我不明白为什么不起作用。 I declared the variable y
in this class:我在这个类中声明了变量y
:
package test;
public class TestConstant
{
public static final double y = 1;
public static void main(String[] args)
{
System.out.println(y);
}
}
It worked fine, I had the output 1
as expected.它工作正常,我得到了预期的输出1
。
Now I'm trying to access this variable outside my class:现在我试图在我的课外访问这个变量:
package test;
public class TestConstant2
{
public static void main(String[] args)
{
System.out.println(y);
}
}
I couldn't run the last source code.我无法运行最后的源代码。 How can I use public constants outside a class it was declared in?如何在声明的类之外使用公共常量?
Constants live in the class where you defined them.常量存在于您定义它们的类中。
package test;
public class TestConstant2
{
public static void main(String[] args)
{
System.out.println(TestConstant.y);
}
}
You have to add the class name in front of the constant:您必须在常量前添加类名:
package test;
public class TestConstant2
{
public static void main(String[] args)
{
System.out.println(TestConstant.y);
}
}
or import it with static或使用静态导入
package test;
import static TestConstant.y;
public class TestConstant2
{
public static void main(String[] args)
{
System.out.println(y);
}
}
BTW: static final variables should be upper case顺便说一句:静态最终变量应该是大写的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.