JAVA私有静态变量如何访问
时间: 2023-05-24 11:05:40 浏览: 473
在Java中,私有静态变量只能通过该类的公共或受保护方法来访问。私有静态变量不能被该类之外的任何其他类直接访问。但是,可以通过在该类中定义公共或受保护方法来访问私有静态变量。
以下是一个示例类,其中包含一个私有静态变量和一个公共方法来访问它:
```
public class MyClass {
private static int myPrivateStaticVariable = 10;
public static int getMyPrivateStaticVariable() {
return myPrivateStaticVariable;
}
}
```
在上面的示例中,私有静态变量`myPrivateStaticVariable`只能通过公共方法`getMyPrivateStaticVariable`来访问。其他类不能直接访问该变量。
以下是如何在另一个类中使用`MyClass`来访问私有静态变量:
```
public class AnotherClass {
public static void main(String[] args) {
int myVariable = MyClass.getMyPrivateStaticVariable();
System.out.println(myVariable);
}
}
```
在上面的示例中,`main`方法通过调用`MyClass`的公共方法`getMyPrivateStaticVariable`来访问私有静态变量。该方法将私有静态变量的值赋给一个局部变量`myVariable`,然后打印这个值。