ใน Java คลาสและ interface ที่เกี่ยวข้องกันจะถูกจัดกลุ่มอยู่ภายใต้ package Package คือ directory ที่เก็บ classes และ interfaces ของ concept เฉพาะ เช่น คลาสและ interface ทั้งหมดที่เกี่ยวกับ input/output operations จะอยู่ใน java.io package
การสร้าง Package
คุณสามารถจัดกลุ่มคลาสและ interface ที่ต้องการภายใต้ package เดียวกันได้โดยแค่ประกาศ package ที่ด้านบนของ Class/Interface (file) โดยใช้ keyword package ดังนี้ -
ตัวอย่าง
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 โปรแกรมที่มี package คุณต้องใช้ option -d ของคำสั่ง javac โดยระบุ destination path ที่ต้องการสร้าง package
Output
javac -d . Sample.java
หากไม่ได้ระบุ destination path package จะถูกสร้างใน current directory
การ Import คลาส
เพื่อเข้าถึง classes/interfaces ที่จัดกลุ่มอยู่ภายใต้ package คุณต้องเพิ่ม location ของ package ใน classpath variable (หรือให้แน่ใจว่า package อยู่ใน current directory) และ import class/interface ของมันโดยใช้ import keyword
ตัวอย่าง
import com.tutorialspoint.mypackage.Sample;
public class Test {
public static void main(String args[]) {
Sample obj = new Sample();
obj.demo();
}
}
Output
This is a method of the sample class
การ Import คลาสซ้ำ
ใช่ คุณสามารถ import คลาสเดียวกันซ้ำได้ใน Java ไม่ได้สร้างปัญหาใดๆ แต่ ไม่ว่าจะ import กี่ครั้ง JVM จะโหลดคลาสเพียงครั้งเดียวเท่านั้น
ตัวอย่าง
ในโปรแกรม Java ต่อไปนี้ เราพยายาม import Sample class ของ package com.tutorialspoint.mypackage เพียงครั้งเดียว
import com.tutorialspoint.mypackage.Sample;
import com.tutorialspoint.mypackage.Sample;
public class Test {
public static void main(String args[]) {
Sample obj = new Sample();
obj.demo();
}
}
Output
Sample class loaded This is a method of the sample class