Public Members: Universal Visibility
What You'll Learn
You'll learn how public members provide unrestricted access from anywhere in your codebase, making them the primary tool for building true public APIs.
The Most Open Access Level
When you declare a member (field, method, constructor) as public, you're granting universal visibility—it can be accessed from any package, by any class, anywhere in your application or even from external code that uses your library.
Think of it like a public park: anyone from anywhere can enter and use it, no restrictions or special permissions needed.
Why Public Members Matter
public members form the contract between your code and the outside world. When designing a library or API, the public members are what you want others to use—they're the documented, stable interface you're committing to support.
package com.library.utils;
public class Calculator {
// Public method - accessible from any package
public int add(int a, int b) {
return a + b;
}
// Public constant - universally readable
public static final double PI = 3.14159;
}
From any other package, you can freely access these members:
package com.myapp.business;
import com.library.utils.Calculator;
public class Accounting {
public void process() {
Calculator calc = new Calculator();
int sum = calc.add(5, 3); // Works!
double pi = Calculator.PI; // Works!
}
}
No special relationship needed—no inheritance, no package proximity, nothing. If it's public, it's accessible.
When to Use Public
Use public for members that are intentionally part of your class's external interface. Be selective: once something is public, changing or removing it can break external code.
Key Takeaway: public members are accessible from anywhere in your codebase, forming the true API surface of your classes and enabling universal visibility across all package boundaries.