Slide 1
Slide 2
Slide 3

Packages in java programming (V62)

No Comments

Packages

Packages are used in Java to prevent naming conflicts, control access, and make searching, locating, and using classes, interfaces, and annotations easier.

A package is a namespace that organizes a set of related classes and interfaces. Think of it like folders in a computer directory: it helps store files logically together and avoids name conflicts.

Types of Packages:

  • Built-in Packages – Provided by Java (e.g., java.util, java.io)
  • User-defined Packages – Created by programmers

User-defined Java Packages

You can define your own packages as a collection of classes, interfaces, and so on. It is a good practice to group related classes that you create, so that programmers can easily identify the classes and interfaces.

Since a package creates a new namespace, there will be no name conflicts with names in other packages. By using packages, it becomes easier to provide access control, and it is also easier to locate related classes.

Creating a Java Package

When creating a package, you should choose a name for the package and include a package statement with that name at the top of all source files that contain the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types defined in that file.

Example: Create Project Name: PackageExample


  • Create package from Source packages name studentpikt and class Student.java

Source Code1: Student.java

Copied!
package studentpikt;

public class Student {
    public void study() {
        System.out.println("Student is studying.");
    }
}

  • Create package from Source packages name teacherpikt and class Teacher.java

Source Code2: Teacher.java

Copied!
package teacherpikt;

public class Teacher {
     public void teach() {
        System.out.println("Teacher is teaching.");
    }
}

  • Use main class PackageExample.java

Source Code3: PackageExample.java

Copied!
package packageexample;
import studentpikt.Student;
import teacherpikt.Teacher;

public class PackageExample {

    public static void main(String[] args) {
        Student s = new Student();
        Teacher t = new Teacher();

        s.study();
        t.teach();
    }
    
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top