Sitemap

Member-only story

Access Modifiers in Java | Explained with examples

3 min readNov 30, 2024

--

Note : This can be last minute read or Cheatsheet. Bookmark this before you lose this gem !

Read for FREE ( Non-member link )

Press enter or click to view image in full size

Understanding Access Modifiers

Imagine access modifiers as different types of doors in a house:

  • Public Door: Everyone can enter
  • Private Door: Only the homeowner can enter
  • Protected Door: Family members and close friends can enter
  • Default (Package-Private) Door: Only people in the same neighborhood can enter

1. Public Access Modifier 🌐

public class House {
// Public method accessible from anywhere
public void welcomeGuests() {
System.out.println("Welcome to everyone!");
}
}
  • Accessible from any class in any package
  • Provides the most open access
  • Use when you want complete visibility

2. Private Access Modifier 🔐

public class BankAccount {
// Private variable - cannot be accessed directly from outside
private double balance;
    // Private method - only accessible within this class
private void…

--

--

Kumar
Kumar

Written by Kumar

15+ years of experience as a Technical recruiter, sharing stories and learnings of individuals whom I recruited.