Let’s modify the MyClass example to include a private variable and a private method. The private modifier is used to restrict access to members (fields and methods) only within the same class. Here’s an updated version of MyClass:
public class MyClass {
// Private variable
private int myPrivateVariable;
// Public method to access the private variable
public void setPrivateVariable(int value) {
myPrivateVariable = value;
}
// Private method
private void myPrivateMethod() {
System.out.println("This is a private method.");
}
// Public method to invoke the private method
public void callPrivateMethod() {
myPrivateMethod();
}
public static void main(String[] args) {
MyClass myObject = new MyClass();
// Access the private variable through a public method
myObject.setPrivateVariable(42);
// Call a public method that invokes the private method
myObject.callPrivateMethod();
}
}
In this example:
myPrivateVariableis a private instance variable, and it can only be accessed or modified within theMyClassitself.setPrivateVariableis a public method that allows external code to set the value ofmyPrivateVariable.myPrivateMethodis a private method that can only be called within theMyClass.callPrivateMethodis a public method that invokes the private method.
By using the private modifier, you can encapsulate the internal details of your class and control access to its members, promoting a more secure and maintainable code structure.