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.

Is declaring a variable as private static varName; any different from declaring a variable private 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?

推荐答案

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

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).

For example:

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);

        // ...
    }
}

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

Java相关问答推荐

Java记录的不同序列化/反序列化

无法在WebSocket onMessage中捕获错误

GSON期间的Java类型擦除

由于 list 中的权限错误,Android未生成

测试何时使用Mockito强制转换对象会导致ClassCastException

使用Room Database删除Jetpack合成中的所有项目后,UI未重新合成

S,要对Java复制构造函数深度克隆所有属性进行单元测试,最可靠的方法是什么?

Docker不支持弹性APM服务器

二进制数据的未知编码/序列化

如何读取3个CSV文件并在控制台中按顺序显示?(Java)

Oj算法 MatrixR032从字符串、归一化和余弦相似度计算创建

从LineChart<;字符串、字符串和gt;中删除数据时出现特殊的ClassCastException;

从映射列表中检索所有键

除0错误/抱歉我的句子是PT

为什么JavaFX MediaPlayer音频播放在Windows和Mac上运行良好,但在Linux(POPOS/Ubuntu)上却有问题?

无法在IntStream上应用Collectors.groupingBy

简化每个元素本身都是 map 列表的列表

Vaadin Flow:设置密码显示按钮属性

为什么 static Thread.currentThread().getName() 和 getName() 之间有区别?

ArrayAdapter 中何时使用构造函数一和构造函数二?