private in java
时间: 2023-11-13 22:08:20 浏览: 33
In Java, the `private` access modifier is used to restrict access to a class member (field or method) within the same class. This means that a `private` member can only be accessed by other members (fields or methods) within the same class, and not by any code outside of the class.
For example, consider the following class:
```
public class MyClass {
private int myPrivateField;
public void setMyPrivateField(int value) {
myPrivateField = value;
}
public int getMyPrivateField() {
return myPrivateField;
}
}
```
Here, `myPrivateField` is declared as `private`, which means that it can only be accessed within the `MyClass` class itself. The `setMyPrivateField()` and `getMyPrivateField()` methods are used to set and retrieve the value of `myPrivateField`, respectively, and can be accessed from outside the class.
However, if you try to access `myPrivateField` directly from outside the class, like this:
```
MyClass obj = new MyClass();
obj.myPrivateField = 10; // Error: myPrivateField has private access in MyClass
```
You will get a compile-time error, because `myPrivateField` is not accessible from outside the class.