共計 567 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 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
的值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完