Lesson Completion
Back to course

The `public` Modifier: Universal Access

Beginner
10 minutes4.8Java

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

In a Nutshell: public is the least restrictive modifier—accessible from anywhere. Use it for stable APIs you want to expose globally. Once something is public, changing it breaks client code, so choose carefully!

Think of Wikipedia. It's public—anyone, anywhere can access it. That's public in Java!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: The Billboard

A billboard on the highway:

  • Everyone can see it (public)
  • A poster in your room: Only you (private)

3. Technical Mastery (The "Deep Dive")

Public Rules

  1. Accessible everywhere: Any package, any class
  2. One public class per file: File name must match class name
  3. API methods: Expose functionality to clients
  4. Breaking changes: Avoid changing public signatures!

4. Interactive & Applied Code

java
// File: User.java package com.myapp; public class User { // PUBLIC class public String name; // ❌ BAD: public field! private int age; // ✅ GOOD: private field public User(String name) { // PUBLIC constructor this.name = name; } public void sayHello() { // PUBLIC method System.out.println("Hello, " + name); } } // File: Main.java (any package) import com.myapp.User; public class Main { public static void main(String[] args) { User user = new User("Alice"); // ✅ Can access from anywhere! user.sayHello(); } }

5. Interview Corner

The "Killer" Interview Question: "Can you have multiple public classes in one file?" Answer: NO! Only one public class per file, and the file name must match the class name. You can have multiple default classes, though.

Pro-Tip: Minimize public APIs. More public = more maintenance burden. Start private, widen only if needed!

Topics Covered

Java FundamentalsModularity

Tags

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

Last Updated

2025-02-01