Private data members keep information safe inside a class. They stop other parts of the program from changing data by mistake.
Private data members in Java
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
name and age. Only methods inside Person can access them.Java
class Person { private String name; private int age; }
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 } }
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.
Practice
1. What is the main purpose of declaring data members as
private in a Java class?easy
Solution
Step 1: Understand private keyword meaning
Theprivatekeyword restricts access to the data member only within the class it is declared.Step 2: Purpose of data hiding
Hiding data prevents outside code from changing it directly, which protects the data integrity.Final Answer:
To hide the data from outside access and protect it -> Option BQuick Check:
Private means hidden and protected [OK]
Hint: Private means only inside class can access it [OK]
Common Mistakes:
- Thinking private allows access from other classes
- Confusing private with public or protected
- Assuming private makes data static
2. Which of the following is the correct way to declare a private integer variable named
age inside a Java class?easy
Solution
Step 1: Check Java syntax for private variables
The correct order is the access modifier first, then the type, then the variable name.Step 2: Validate each option
private int age; follows the correct syntax:private int age;. Others have wrong order or wrong type keyword.Final Answer:
private int age; -> Option AQuick Check:
Access modifier + type + name [OK]
Hint: Access modifier comes before type and name [OK]
Common Mistakes:
- Placing 'private' after the type
- Using 'integer' instead of 'int'
- Incorrect order of keywords
3. What will be the output of the following Java code?
class Person {
private String name = "Alice";
public String getName() {
return name;
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person();
System.out.println(p.getName());
}
}medium
Solution
Step 1: Understand private variable access
The variablenameis private but accessed via the public methodgetName().Step 2: Trace the method call and output
The method returns "Alice", soSystem.out.printlnprints "Alice".Final Answer:
Alice -> Option CQuick Check:
Private data accessed via public method returns value [OK]
Hint: Use public methods to access private data [OK]
Common Mistakes:
- Expecting direct access to private variable
- Thinking private variable is null by default
- Assuming compilation error due to private access
4. Identify the error in the following Java code snippet:
class Car {
private int speed;
public void setSpeed(int speed) {
speed = speed;
}
public int getSpeed() {
return speed;
}
}medium
Solution
Step 1: Analyze the setter method
The setter method assigns the parameterspeedto itself, not to the private variable.Step 2: Understand variable shadowing
The parameterspeedshadows the private variable. To update the private variable, usethis.speed = speed;.Final Answer:
The setter method does not update the private variable -> Option AQuick Check:
Use 'this' to update private variable in setter [OK]
Hint: Use 'this.' to refer to class variable in setters [OK]
Common Mistakes:
- Not using 'this' keyword in setter
- Making private variable public unnecessarily
- Changing getter return type incorrectly
5. You want to keep a private list of student names inside a class and allow adding names but prevent direct access to the list. Which approach correctly uses private data members and methods?
hard
Solution
Step 1: Understand data hiding and controlled access
Private list hides data; public method to add controls how data changes.Step 2: Evaluate options for safe access
Declare private List<String> students; provide public addStudent(String name) method; no public getter for the list. hides list and allows adding names safely. Declare public List<String> students; allow direct access and modification. exposes list directly, unsafe. Declare private List<String> students; provide public getStudents() returning the list directly. exposes list directly via getter, unsafe. Declare private List<String> students; no methods to add or access students. provides no way to add or access data.Final Answer:
Declare private List<String> students; provide public addStudent(String name) method; no public getter for the list. -> Option DQuick Check:
Private data + public methods for controlled access [OK]
Hint: Use private list + public add method, no direct getter [OK]
Common Mistakes:
- Making list public and exposing internal data
- Returning private list directly allowing modification
- Not providing any method to modify or access data
