Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa import và static import trong Java?


Chúng ta có thể dùng câu lệnh import để import class và interface của một package cụ thể. Khi dùng import statement, không cần dùng fully qualified name và có thể dùng tên ngắn trực tiếp. Chúng ta dùng static import để import static member từ một class và package cụ thể. Khi dùng static import thì không cần dùng tên class để truy cập static member và có thể dùng trực tiếp.

Câu lệnh import

  • Để truy cập class hoặc method từ package khác, chúng ta cần dùng fully qualified name hoặc dùng câu lệnh import.
  • Class hoặc method cũng phải accessible. Khả năng truy cập dựa trên access modifiers.
  • Private members chỉ accessible trong cùng class. Vì vậy chúng ta không thể truy cập private member ngay cả với fully qualified name hoặc import statement.
  • Gói java.lang được import tự động vào code của chúng ta bởi Java.

Ví dụ

import java.util.Vector; 
public class ImportDemo { 
    public ImportDemo() { 
        //Imported using keyword, hence able to access directly in the code without package qualification. 
        Vector v = new Vector(); 
        v.add("Tutorials"); 
        v.add("Point"); 
        v.add("India"); 
        System.out.println("Vector values are: "+ v); 
        //Package not imported, hence referring to it using the complete package. 
        java.util.ArrayList list = new java.util.ArrayList(); 
        list.add("Tutorix"); 
        list.add("India"); 
        System.out.println("Array List values are: "+ list); 
    } 
    public static void main(String arg[]) { 
        new ImportDemo(); 
    } 
}

Kết quả

Vector values are: [Tutorials, Point, India] Array List values are: [Tutorix, India]

Static Import Statement

  • Static imports sẽ import tất cả static data để có thể dùng không cần tên class.
  • Một khai báo static import có hai dạng: một import một static member cụ thể gọi là single static import và một import tất cả static members của một class gọi là static import on demand.
  • Static imports được giới thiệu từ Java 5.
  • Một ưu điểm của static imports là giảm phím gõ và tái sử dụng.

Ví dụ

import static java.lang.System.*; //Using Static Import 
public class StaticImportDemo { 
    public static void main(String args[]) { 
        //System.out is not used as it is imported using the keyword static. 
        out.println("Welcome to Tutorials Point"); 
    } 
}

Kết quả

Welcome to Tutorials Point