Package-private
- Java course
- Intermediate
- Lesson 27/116
- 4 min
Learn package-level visibility.
Package visibility
If you do not write an access modifier on a field or method, package-private visibility applies. Classes in the same package can access the member; classes in a different package cannot. It is less strict than private and less open than public.
Example: class Config { String version; }. Here version has no modifier; it is package-private. Another class in the same package can write config.version to access it. If access is attempted from a different package, a compile error occurs. Package visibility lets classes in the same package work closely; it hides them from outside packages.
When to use package visibility?
Package visibility is useful when classes in the same package work closely together. It is suitable for members shared between test classes, helper classes or internal modules. It blocks access from outside packages but is free within the package.
Example: In a report package, suppose ReportBuilder and ReportData classes exist. If ReportData's fields are package-private, ReportBuilder can access them directly. A class outside the report package cannot. This provides a balance of intra-package freedom and external privacy. When private is too strict and public too open, package visibility is a good middle ground.
Practice Define Config with package visibility
Define a class Config. Add a String version field (no modifier). Add a public String toString() method returning "Version: " + version. In main create a Config instance, assign a value to version and print the instance with println.
Starter code
// Define the Config class
// Add a version field with package visibility
// Add toString and mainSample solution
class Config {
String version;
public String toString() {
return "Version: " + version;
}
public static void main(String[] args) {
Config c = new Config();
c.version = "1.0";
System.out.println(c);
}
}Expected output
Version: 1.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the package-private field
class Config {
____ version;
}
class Config {
String version;
}
Explanation: Without a modifier, the field is package-private.
2 Match access levels
| Term | Meaning |
|---|---|
private |
Class only |
(no modifier) |
Same package |
protected |
Subclasses + package |
public |
Everywhere |
3 What happens when no modifier is written on a field?
- It becomes private
- It becomes protected
- It becomes package-private Correct answer
- It becomes public
Explanation: It becomes package-private — accessible within the same package.