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.