Trong Java, class và interface liên quan nhau được nhóm dưới một package. Package là thư mục lưu class/interface của một khái niệm. Ví dụ: mọi class/interface liên quan I/O nằm trong java.io.
Tạo package
Nhóm class/interface cần thiết dưới một package bằng từ khóa package ở đầu file:
Ví dụ
package com.tutorialspoint.mypackage; public class Sample { public void demo() { System.out.println("This is a method of the sample class"); } public static void main(String args[]) { System.out.println("Hello how are you......"); } }
Compile chương trình có package
Khác chương trình thường, compile cần option -d của javac chỉ định destination path tạo package.
javac -d . Sample.java
Nếu không chỉ định destination, package tạo ở thư mục hiện tại.
Thực thi .class trong package
Chạy byte code cần absolute class name (tên kèm package):
java com.tutorialspoint.mypackage.Sample Hello how are you......
Truy cập nội dung package
Để dùng class/interface trong package, thêm vị trí package vào classpath (hoặc đảm bảo package ở current directory) và import bằng từ khóa import.
Ví dụ
import com.tutorialspoint.mypackage.Sample; public class Test { public static void main(String args[]) { Sample obj = new Sample(); obj.demo(); } }
Kết quả
This is a method of the sample class