Lesson Completion
Back to course

The `private` Modifier: Maximum Encapsulation

Beginner
10 minutes4.7Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: private is the most restrictive access modifier. Private members are accessible only within the same class—not even subclasses or same-package classes can access them. Use private for implementation details you want to hide completely.

Think of your phone's lock screen. The PIN is private—only you (the class) know it. Not your family (package), not your kids (subclasses), nobody else!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Diary with a Lock

Your diary:

  • Private thoughts: Only you can read
  • Published book: Anyone can read (public)

private fields are like locked diary entries!


3. Technical Mastery (The "Deep Dive")

Private Rules

  1. Class-level only: Accessible within same class
  2. Not inherited: Subclasses can't access
  3. Best for fields: Almost always make fields private
  4. Helper methods: Private implementation details

4. Interactive & Applied Code

java
public class BankAccount { private double balance; // PRIVATE: implementation detail private String pin; // PRIVATE: sensitive data public void deposit(double amount) { if (isValidAmount(amount)) { // Private helper balance += amount; } } private boolean isValidAmount(double amount) { return amount > 0; // Private validation logic } public double getBalance() { return balance; // Public getter for controlled access } } class SubAccount extends BankAccount { void test() { // balance = 100; // ❌ ERROR: Can't access private field! deposit(100); // ✅ OK: Use public method } }

5. Interview Corner

The "Killer" Interview Question: "Can two objects of the same class access each other's private fields?" Answer: YES! private means class-level, not object-level:

java
class Point { private int x; boolean equals(Point other) { return this.x == other.x; // ✅ Can access other's private x! } }

Pro-Tip: Always start with private, then widen if needed. Can't go backwards without breaking code!

Topics Covered

Java FundamentalsModularity

Tags

#java#packages#access-modifiers#encapsulation#scope

Last Updated

2025-02-01