私人能見度
private
可見性允許變數僅由其類訪問。它們通常與 public
getter 和 setter 一起使用。
class SomeClass {
private int variable;
public int getVariable() {
return variable;
}
public void setVariable(int variable) {
this.variable = variable;
}
}
public class SomeOtherClass {
public static void main(String[] args) {
SomeClass sc = new SomeClass();
// These statement won't compile because SomeClass#variable is private:
sc.variable = 7;
System.out.println(sc.variable);
// Instead, you should use the public getter and setter:
sc.setVariable(7);
System.out.println(sc.getVariable());
}
}