Private data members keep information safe inside a class. They stop other parts of the program from changing data by mistake.
0
0
Private data members in Java
Introduction
When you want to hide details of how data is stored inside a class.
When you want to control how data is changed or accessed.
When you want to prevent accidental changes from outside the class.
When you want to make your code easier to fix and understand later.
Syntax
Java
class ClassName { private DataType variableName; }
The keyword private means only code inside the class can use this variable.
Other parts of the program cannot see or change private data members directly.
Examples
This class has two private data members:
name and age. Only methods inside Person can access them.Java
class Person { private String name; private int age; }
The
balance is private so no one outside the class can change it directly.Java
class BankAccount { private double balance; }
Sample Program
This program shows a Car class with private data members model and year. We use a constructor to set them and a method to show them. Trying to change model directly outside the class causes an error.
Java
class Car { private String model; private int year; public Car(String model, int year) { this.model = model; this.year = year; } public void displayInfo() { System.out.println("Model: " + model); System.out.println("Year: " + year); } } public class Main { public static void main(String[] args) { Car myCar = new Car("Toyota", 2020); myCar.displayInfo(); // The following line would cause an error if uncommented: // myCar.model = "Honda"; // Error: model has private access in Car } }
OutputSuccess
Important Notes
To access or change private data, use public methods called getters and setters.
Private data members help keep your program safe and organized.
Summary
Private data members hide data inside a class.
Only code inside the class can use private variables directly.
Use public methods to safely access or change private data.