[LTM] Chương 4.10 : Interface

Người đăng: share-nhungdieuhay on Thứ Hai, 24 tháng 3, 2014


Giao tiếp (Interface)

  1. Giới thiệu
  2. Định nghĩa giao tiếp
  3. Thực thi giao tiếp
  4. Ví dụ

Giao tiếp (Interface)
Trong đa thừa kế, lớp con có thể thừa kế từ nhiều lớp khác nhau. (cần thiết trong lập trình)
Java không hỗ trợ đa thừa kế.
Tuy nhiên, Java đã đưa ra khái niệm interface:

  • cho phép đa kế thừa trong Interface.
  • Đ/n: Một giao tiếp là một tập hợp các định nghĩa phương thức trừu tượng (không có cài đặt) và có thể định nghĩa các hằng.
  • Với giao tiếp ta có thể xác định một lớp phải làm gì nhưng không xác định cách làm thế nào.


Khai báo giao tiếp (Interface)
Cú pháp chung:
[public] interface <InterfaceName> extends SuperInterfaces
{
//Thân giao tiếp
}
Nếu không có public thì giao tiếp sẽ  chỉ có thể truy xuất bởi các lớp được định nghĩa trong cùng gói với giao tiếp.
SuperInterfaces: có thể là 1 ds interfaces cha (ngăn cách ,)
Thân giao tiếp chứa các khai báo phương thức cho tất cả các phương thức có trong giao tiếp. (không cung cấp cách cài đặt).
Interfaces - ex
public interface CalculatorInterface
{
 public double add(double x, double y);
 public double sub(double x, double y);
 public double mul(double x, double y);
 public double div(double x, double y);
}
Interface Const {
Double PI=3.14;
String DONVI_S=  “cm2 “ ;
String DONVI_S= “ cm “;
}

Thực thi giao tiếp
Một lớp thực thi một giao tiếp tuân theo những quy ước đã được khai báo trong giao tiếp đó.
Khai báo một lớp thực thi một (nhiều) giao tiếp, dùng mệnh đề implements:
class <ClassName> [extends] implements <InterfaceNames>
//Bổ sung các tp;
//Cài đặt các phương thức đã khai báo trong interface;
}
<InterfaceNames>: danh sách các giao tiếp


class CalculatorTest implements CalculatorInterface  {
 public double add(double x, double y)  {   return x+y;  }
 public double sub(double x, double y)  {   return x-y;  }
 public double mul(double x, double y)  {   return x*y;  }
 public double div(double x, double y)  {return x/y;   }
 public static void main(String[] args) {
  CalculatorInterface cal=new CalculatorTest();
double x,y,z;
x=10; y=5;
System.out.println(x+"+"+y+"="+ cal.add(x,y));
System.out.println(x+"-"+y+"="+ cal.sub(x,y));
System.out.println(x+"*"+y+"="+ cal.mul(x,y));
System.out.println(x+"/"+y+"="+ cal.div(x,y));
  }
}
Implementing Multiple Interfaces

  • An interface can extend zero or more interfaces
  • Multiple interfaces can be implemented in a single class.
  • This implementation provides the functionality of multiple inheritance.
  • Implement multiple interfaces by placing commas between the interface names when implementing them in a class.
  • A class must implement all inherited interface methods

Ex of Implementing Multiple Interfaces

{ 0 nhận xét... read them below or add one }

Đăng nhận xét