If no access modifier is explicitly declared in Java, the member or class receives package-private access (also known as default access). This means it can be accessed only by other classes within the same package and remains hidden from classes in different packages.
Key Points:
• Package-private is the default access level in Java. • Accessible only within the same package. • Cannot be accessed from classes located in other packages. • Provides better encapsulation than public access while allowing related classes in a package to collaborate.
Example:
Suppose a banking application has AccountService and TransactionService in the same package. A package-private method in AccountService can be accessed by TransactionService, but not by classes outside that package.
Code Example:
class AccountService {
void validateAccount() {
System.out.println("Validating account...");
}
}Interview Tip:
A concise interview answer is: "If no access modifier is specified in Java, the access level becomes package-private. Such members are accessible only within the same package and cannot be accessed from classes in other packages."