private fields
- Java course
- Intermediate
- Lesson 24/116
- 4 min
Learn field hiding with private.
private fields
Encapsulation protects a class's fields from outside access. By making fields private, you prevent direct access. Data can then only be changed through the class's own methods; external interference is prevented.
Example: class Account { private double balance; }. Here balance is private. If you write Account a = new Account(); a.balance = 100; you get a compile error; because balance cannot be accessed from outside the class. Access is provided through getter and setter methods; these come in later lessons. Encapsulation protects data integrity.
Why private?
Making fields private keeps data under control. It prevents unwanted value assignments from outside. For example, you can stop a balance field from receiving a negative value.
Without encapsulation, a.balance = -50; can be written and the account drops to a negative balance. With private you prevent this; the balance is only changed through a setter method, and the setter rejects negative values. This ensures the data always stays valid. Encapsulation hides the class's internal design from outside; changes happen inside the class, outside code is not affected.
Practice Add a private field to Account
Define a class Account. Add a private double balance field. Write a void deposit(double amount) method; its body runs balance += amount;. Add a double getBalance() method returning balance. In main create an Account instance, call deposit(100) and print the result of getBalance().
Starter code
// Define the Account class
// Add a private balance field
// Write deposit and getBalance methodsSample solution
class Account {
private double balance;
void deposit(double amount) {
balance += amount;
}
double getBalance() {
return balance;
}
public static void main(String[] args) {
Account a = new Account();
a.deposit(100);
System.out.println(a.getBalance());
}
}Expected output
100.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when you access a private double balance field from outside?
- The value resets to zero
- A compile error occurs Correct answer
- The value is assigned
- The class is deleted
Explanation: private fields cannot be accessed from outside; a compile error occurs.
2 Make the field private
class Account {
____ double balance;
}
class Account {
private double balance;
}
Explanation: The balance field is now private.
3 Match access modifiers
| Term | Meaning |
|---|---|
private |
Class only |
public |
Everywhere |
protected |
Subclasses |
(no modifier) |
Same package |