Java Packages and Accessing Classes


Table of Contents

  1. Introduction to Java Packages
  2. What is a Java Package?
  3. Types of Packages in Java
    • Built-in Packages
    • User-defined Packages
  4. Creating Packages in Java
    • Syntax and Examples
    • Package Directory Structure
  5. Accessing Classes from Packages
    • Import Statement
    • Access Modifiers and Package Access
  6. The ‘import’ Statement
    • Importing Specific Classes
    • Importing All Classes
    • Static Imports
  7. The Default Package
  8. Access Control in Packages
    • Public, Protected, Default, and Private Access Modifiers
    • Accessing Classes in Different Packages
  9. Best Practices for Using Packages
  10. Summary

1. Introduction to Java Packages

In Java, packages are used to group related classes and interfaces together. A package helps to organize your code in a modular way, providing a namespace for your classes and avoiding name conflicts. Packages are also crucial for managing access control to classes, interfaces, and other members within a program.

A package in Java serves two major purposes:

  • Organization: By grouping related classes and interfaces, packages make it easier to manage and locate classes.
  • Access control: Packages help in controlling access to classes, restricting access to specific parts of the code using access modifiers.

In this module, we will explore what Java packages are, how to create and use them, and how to access classes from different packages.


2. What is a Java Package?

A Java package is essentially a directory or folder that contains related classes and interfaces. These classes and interfaces may also contain other packages, known as sub-packages.

Packages provide a way to avoid name conflicts. For instance, two different libraries can have classes with the same name, but if these classes are in different packages, there won’t be any conflicts.

Syntax:

package packageName;

A package declaration must be the first statement in a Java source file. If no package is specified, the class is placed in the default package.


3. Types of Packages in Java

In Java, packages can be divided into two types:

1. Built-in Packages

Java provides several built-in packages that contain pre-defined classes and interfaces. These packages are part of the Java API and provide a wide range of functionality for input-output operations, networking, utilities, collections, and more. Some commonly used built-in packages are:

  • java.lang: Contains fundamental classes like String, Math, Object, etc.
  • java.util: Contains utility classes like ArrayList, HashMap, Date, etc.
  • java.io: Provides classes for input-output functionality, such as File, BufferedReader, PrintWriter, etc.

2. User-defined Packages

You can create your own custom packages, which helps in organizing your classes logically according to the functionality or the domain they represent. For instance, a project for an online store might have packages such as com.store.inventory, com.store.payment, com.store.shipping, etc.


4. Creating Packages in Java

To create a package, you can use the package keyword followed by the package name at the very top of your Java source file.

Syntax:

package packageName;

For example, to create a package called com.store.inventory, you would add the following at the top of the Java file:

package com.store.inventory;

public class Product {
// Class implementation here
}

Package Directory Structure

When you create a package, you should follow a directory structure that mirrors the package name. For the above example, your file structure would look like this:

/com/store/inventory/Product.java

Java uses this folder structure to determine which classes belong to which package. When compiling, the directory structure must be maintained.

Compiling Classes in a Package

To compile a class that is part of a package, use the following command:

javac com/store/inventory/Product.java

5. Accessing Classes from Packages

To access a class that is part of a package, you need to import it into your Java program. There are two ways to import classes from a package: using the import statement and by specifying the full path to the class.

Import Statement

The import statement allows you to access classes from other packages. You can import specific classes or all classes from a package.

Importing Specific Classes:

If you want to import a specific class, use the following syntax:

import packageName.ClassName;

Example:

import com.store.inventory.Product;

public class Main {
public static void main(String[] args) {
Product p = new Product();
}
}

Importing All Classes in a Package:

If you want to import all classes from a package, you can use the wildcard *:

import com.store.inventory.*;

However, using * is generally not recommended because it can import unnecessary classes, leading to inefficient code and potential naming conflicts.


6. The ‘import’ Statement

The import statement simplifies access to classes and interfaces by allowing you to refer to them by their short names rather than their fully qualified names.

Importing Specific Classes

If you only need a single class, you can import just that class:

import java.util.Scanner;

Importing All Classes

To import all the classes from a package:

import java.util.*;

Static Imports

Java also provides static imports, which allow you to access static members (fields or methods) of a class without the need to qualify them with the class name.

import static java.lang.Math.*;

Now, you can use methods like sqrt() or constants like PI directly without prefixing them with Math..


7. The Default Package

If a class is not part of any package, it is placed in the default package. However, using the default package is not recommended for larger projects, as it can lead to confusion and a lack of organization.

Example:

public class Product {
// Class without a package declaration
}

This class will be part of the default package, and you don’t need to import it. However, for projects with many classes, it’s much better to use named packages.


8. Access Control in Packages

Access control is a key feature of Java’s package system. Java provides access modifiers that determine the visibility of classes, fields, and methods.

Public Access Modifier

The public access modifier allows classes, methods, or fields to be accessed from any other class, even if they are in different packages.

public class Product {
public void displayDetails() {
// Code
}
}

Protected Access Modifier

The protected modifier allows access to the class members only within the same package and subclasses (even if they are in a different package).

Default (Package-Private) Access Modifier

When no access modifier is specified, it means the member is package-private and is only accessible to other classes in the same package.

Private Access Modifier

The private modifier restricts access to the class members only to the current class.


9. Best Practices for Using Packages

  1. Use meaningful names: Package names should clearly indicate the functionality or domain they represent (e.g., com.bank.payment, com.company.hr).
  2. Follow a standard naming convention: Package names should be lowercase and follow the reverse domain name convention (e.g., com.companyname.projectname).
  3. Avoid using the default package: Always define packages for your classes to improve organization and avoid name conflicts.
  4. Keep packages focused: Avoid creating overly large packages. Instead, break up functionality into smaller, focused packages.

10. Summary

In this module, we covered the concept of Java packages and how they are used to organize and manage classes within a project. We explored the package declaration, import statement, and access control in packages. Key points include:

  • Packages help organize classes, avoid name conflicts, and improve maintainability.
  • Java provides both built-in and user-defined packages.
  • The import statement simplifies accessing classes from other packages.
  • Access modifiers control visibility and accessibility across packages.

By using packages effectively, Java developers can maintain clean, modular, and maintainable code that is easier to manage and scale.