Mastering Java Access Modifiers: Packages, Public, Protected, and Private Explained
This article explains Java's access control hierarchy—public, protected, package‑private, and private—detailing package naming conventions, the role of the package keyword, how each modifier affects class members and classes, and includes practical code examples.
Package Access
In Java each .java file is a compilation unit; at most one public class may appear per file and its name must match the file name.
Packages group related classes. Declaring package com.example.project; places the class in a namespace that corresponds to a directory hierarchy. The full directory path becomes the package name, typically starting with the reverse of the organization’s Internet domain to guarantee uniqueness.
Access Modifiers
Package‑private (default)
Members without an explicit modifier have package‑private access: they are visible to all classes in the same package but not to classes in other packages.
public
Members declared public are accessible from any class.
private
Only the defining class can access private members. Common practice is to keep fields private and expose them through public getter/setter methods.
public class BaseElement {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}Frameworks such as Lombok can generate these methods automatically with @Data.
Private constructors can be used to force object creation through a controlled static method, a pattern often employed for singletons or factory methods.
class Sundae {
private Sundae() {}
static Sundae makeASundae() {
return new Sundae();
}
}protected
protectedmembers are accessible to subclasses regardless of package, and also retain package‑private visibility for other classes in the same package.
Class‑Level Access
Top‑level classes cannot be declared private or protected. Their visibility is limited to either package‑private (default) or public.
Private top‑level classes would be inaccessible to any other class.
Only package‑private or public visibility is allowed for top‑level classes; inner classes may use other modifiers.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
