Packages
Packages are an encapsulation mechanism that group related classes and interfaces into a single unit.
What is a package?
A package groups related types (classes/interfaces) for modularity, naming, and access control.
Examples
- java.sql — classes and interfaces related to database operations.
- java.io — classes and interfaces for file I/O operations.
Main advantages
- Resolve name conflicts (unique identification).
- Improve modularity of the application.
- Improve maintainability.
- Provide security for components (access control).
Naming convention
Use the internet domain name in reverse followed by module/submodule/class. Example:
- com.icicibank — reversed domain
- loan — module
- housing — submodule
- Account — class
Code example
Compiling & class file placement
javac Test.java
The generated .class file is placed in the current working directory.
javac -d
-d specifies the destination root where the .class files are placed (creates folder structure for the package if needed).
- If destination doesn't exist you can specify another path:
javac -d F: Test.java - If specified directory is not present and not creatable: compile error (directory not found).
Execution
Run using fully qualified name:
Rules & Conclusion
- At most one package statement is allowed per source file.
- If used, the package declaration must be the first non-comment statement in the file.
- Valid Java source file structure (when package is present):
- package statement
- import statements
- class / interface / enum declaration
Access modifiers (summary)
Recommended: make data members private, expose methods as public when needed.
| Context | public | private | protected | default |
|---|---|---|---|---|
| Within same class | Allowed | Allowed | Allowed | Allowed |
| Child class (same package) | Allowed | Not allowed | Allowed | Allowed |
| Non-child class (same package) | Allowed | Not allowed | Allowed | Allowed |
| Child class (outside package) | Allowed | Not allowed | Allowed (use child reference) | Not allowed |
| Non-child class (outside package) | Allowed | Not allowed | Not allowed | Not allowed |
Access order (least → most permissive): private < default < protected < public