Java中私有静态变量的用途是什么? [英] What is the use of a private static variable in Java?

查看:127
本文介绍了Java中私有静态变量的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果变量声明为 public static varName; ,那么我可以从任何地方访问它,因为 ClassName.varName 。我也知道静态成员由类的所有实例共享,并且不会在每个实例中重新分配。

If a variable is declared as public static varName;, then I can access it from anywhere as ClassName.varName. I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.

将变量声明为 private static varName; 与声明变量 private varName;

Is declaring a variable as private static varName; any different from declaring a variable private varName;?

两者都不同无法从任何其他类中以 ClassName.varName ClassInstance.varName 的形式访问它。

In both cases it cannot be accessed as ClassName.varName or as ClassInstance.varName from any other class.

将变量声明为静态会给它带来其他特殊属性吗?

Does declaring the variable as static give it other special properties?

推荐答案

当然它可以可以作为 ClassName.var_name 访问,但只能从定义它的类中进行访问 - 这是因为它是 private

Ofcourse it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is private.

public static private static 变量通常是用于常量。例如,许多人不喜欢在代码中硬编码常量;他们喜欢使用有意义的名称制作 public static private static 变量,并在其代码中使用该变量,使代码更具可读性。 (你还应该制作这样的常量 final )。

public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).

例如:

public class Example {
    private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
    private final static String JDBC_USERNAME = "username";
    private final static String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        Connection conn = DriverManager.getConnection(JDBC_URL,
                                         JDBC_USERNAME, JDBC_PASSWORD);

        // ...
    }
}

无论你是 public 还是 private 取决于你是否希望变量在课堂外可见。

Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.

这篇关于Java中私有静态变量的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆