The private access modifier keeps parts of your code hidden and safe inside a class. It helps control what other parts of the program can see or change.
Private access modifier in Java
private dataType variableName; private returnType methodName(parameters) { // method body }
Private members can only be used inside the same class.
Other classes cannot access private variables or methods directly.
age inside a class.private int age;
private void showMessage() { System.out.println("Hello!"); }
name and method setName are private, so only the Person class can use them.public class Person { private String name; private void setName(String newName) { name = newName; } }
This program shows a Car class with a private variable model and a private method displayModel. The private method is called inside a public method show. The main method creates a Car object and calls show to print the model.
public class Car { private String model; public Car(String model) { this.model = model; } private void displayModel() { System.out.println("Car model: " + model); } public void show() { displayModel(); } public static void main(String[] args) { Car myCar = new Car("Toyota"); myCar.show(); // myCar.displayModel(); // This line would cause an error if uncommented } }
Trying to access private members from outside the class will cause a compile error.
Use public methods to safely access or change private variables (this is called encapsulation).
Private access helps keep your code clean and less error-prone.
Private members are only visible inside their own class.
They help protect data and hide details from other parts of the program.
Use public methods to interact with private data safely.
