0
0
Javaprogramming~15 mins

Private access modifier in Java

Choose your learning style8 modes available
menu_bookIntroduction

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.

When you want to hide details of how a class works from other classes.
When you want to protect important data inside a class from being changed directly.
When you want to control access to variables or methods through special functions.
When you want to keep your code organized and prevent accidental mistakes.
When you want to follow good programming practice by encapsulating data.
regular_expressionSyntax
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.

emoji_objectsExamples
line_end_arrow_notchThis declares a private integer variable named age inside a class.
Java
private int age;
line_end_arrow_notchThis declares a private method that prints a message. It can only be called inside the class.
Java
private void showMessage() {
    System.out.println("Hello!");
}
line_end_arrow_notchHere, both the variable name and method setName are private, so only the Person class can use them.
Java
public class Person {
    private String name;

    private void setName(String newName) {
        name = newName;
    }
}
code_blocksSample Program

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.

Java
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
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Trying to access private members from outside the class will cause a compile error.

line_end_arrow_notch

Use public methods to safely access or change private variables (this is called encapsulation).

line_end_arrow_notch

Private access helps keep your code clean and less error-prone.

list_alt_checkSummary

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.