Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

  • packages are mechanism for organizing classes and interfaces into namespace, preventing naming conflicts, improving code maintainability, and controlling access to classes.
  • They group related code together, similar to folders in a file system.

defining a package

  • a package is defined using the package keyword at the beginning of a java source file. It specifies the namespace where the class resides.
// File: com/example/MyClass.java
package com.example;

public class MyClass {
    public void display() {
        System.out.println("Hello from MyClass!");
    }
}

classpath

  • the classpath is an environment variable or command line parameter that tells the java compiler and jvm where to find the compiled .class files and libs.
  • purpose -
    • helps locate classes in packages when compiling or running java programs.
    • specifies directories, JAR files, or ZIP file containing class files.

package naming

  • package names follow a hierarchical naming convention to avoid conflicts and ensure uniqueness.
  • conventions -
    • use lowercase letters.
    • follow reverse domain name structure to ensure uniqueness.
  • rules -
    • must be valid identifiers (no spaces, special characters, or reserved keywords).
    • should map to directory structure.
    • avoid using java keywords or starting with numbers.

accessibility of packages

  • packages control access to classes and their members using [[access modifiers]]. the accessibility of package members depends on these modifiers and package structure.

using package members

  • to use classes, interfaces or other members from a package, you need to either import them or use their fully qualified name.
  • using fully qualified name -
com.example.MyClass obj = new com.example.MyClass(); obj.display()
  • using import - import a specific class or an entire packages to use its members without the fully qualified name.
import packageName.ClassName;
  • static imports
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

public class Test {
    public static void main(String[] args) {
        System.out.println("PI: " + PI); // No Math.PI needed
        System.out.println("Sqrt: " + sqrt(16)); // No Math.sqrt needed
    }
}