在Java中,私有变量只能在其所属类的内部访问,不能在其他类中直接访问。但是,可以通过提供公共的访问方法(getter和setter方法)来间接访问私有变量。
以下是一个示例代码:
public class MyClass {
private int myPrivateVariable;
public int getMyPrivateVariable() {
return myPrivateVariable;
}
public void setMyPrivateVariable(int value) {
myPrivateVariable = value;
}
}
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.setMyPrivateVariable(10);
System.out.println(myObject.getMyPrivateVariable());
}
}
在上面的代码中,myPrivateVariable
是一个私有变量。通过提供getMyPrivateVariable()
和setMyPrivateVariable()
方法,可以在Main
类中间接地访问和修改myPrivateVariable
的值。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:如何通过反射访问java私有变量