简体   繁体   English

如何在其他类中使用公共常量?

[英]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.

相关问题 如何使用其他类中的对象? - How can I use objects in other classes? 为什么我不能对从HashMap获得的对象使用其他类的公共方法? - Why can I not use the public methods from other classes on an object that I got from a HashMap? 如何在Java中的其他类中使用在公共类中定义的变量? - How to use variables defined in a public class in other classes in java? 如何在其他 Scala 类中使用处理函数? - How can I use Processing functions in other Scala classes? 如何在Java中的其他类中使用静态方法 - How can I use static methods in other classes in java 如何在具有不同常量的代码上使用提取方法? - How can I use Extract Method on code that has different constants? 如何在Hibernate本机查询中使用常量? - How can I use constants in Hibernate native query? 如何正确实例化类中的公共类+数据结构,以便其他对象可以使用它? - How do I correctly instantiate a public class+data structure in a class so that other objects can use it? 如何在类路径上比较两个类的公共API? - How can I compare the public API of two classes on the classpath? 如何在我当前班级的其他课程中使用方法 - How can I use a method in one of my other classes in my current class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM