Packages In Java

Java Packages — Notes

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.
Packages example

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.loan.housing.Account
  • com.icicibank — reversed domain
  • loan — module
  • housing — submodule
  • Account — class

Code example

package com.code.java; public class Test { public static void main(String[] args) { System.out.println("hello"); } }

Compiling & class file placement

javac Test.java
The generated .class file is placed in the current working directory.

javac example

javac -d

javac -d . Test.java

-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:

java com.code.java.Test

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):
  1. package statement
  2. import statements
  3. class / interface / enum declaration
file structure

Access modifiers (summary)

Recommended: make data members private, expose methods as public when needed.

Context public private protected default
Within same class AllowedAllowedAllowedAllowed
Child class (same package) AllowedNot allowedAllowedAllowed
Non-child class (same package) AllowedNot allowedAllowedAllowed
Child class (outside package) AllowedNot allowedAllowed (use child reference)Not allowed
Non-child class (outside package) AllowedNot allowedNot allowedNot allowed

Access order (least → most permissive): private < default < protected < public

0 Comments