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

Interface trong Java


Interface là kiểu tham chiếu (reference type) trong Java. Nó tương tự như class. Là tập hợp các phương thức trừu tượng (abstract methods). Lớp implements interface, từ đó kế thừa các phương thức trừu tượng của interface.

Ngoài abstract method, interface cũng có thể chứa hằng số (constants), default method, static method, và nested type. Body method chỉ tồn tại cho default method và static method.

Viết interface tương tự viết class. Nhưng class mô tả thuộc tính và hành vi của object. Interface chứa hành vi mà class triển khai.

Trừ khi class triển khai interface là abstract, tất cả method của interface phải được định nghĩa trong class.

Interface tương tự class ở những điểm:

  • Interface có thể chứa bất kỳ số lượng method.
  • Interface viết trong file .java, tên interface trùng tên file.
  • Bytecode của interface nằm trong file .class.
  • Interface nằm trong package, file bytecode tương ứng phải trong cấu trúc thư mục khớp tên package.

Tuy nhiên, interface khác class ở vài điểm:

  • Không thể khởi tạo (instantiate) interface.
  • Interface không chứa constructor.
  • Tất cả method trong interface là abstract (trừ default/static).
  • Interface không chứa instance field. Chỉ field static final.
  • Interface không được extends bởi class; nó được implements bởi class.
  • Interface có thể extends nhiều interface.

Khai báo Interface

Từ khóa interface dùng để khai báo interface. Ví dụ đơn giản:

Ví dụ

Dưới đây là ví dụ interface:

/* File name : NameOfInterface.java */
import java.lang.*; // Any number of import statements
public interface NameOfInterface {
    // Any number of final, static fields
    // Any number of abstract method declarations
}