Java Tut 31 : Java Interface ( Giao diện) 0 (0)
https://www.w3schools.com/java/java_interface.asp Phần này google dịch hơi khó hiểu .
Một cách khác để đạt được sự trừu tượng trong Java, là với các giao diện.
An interfacelà một ” lớp trừu tượng ” hoàn toàn được sử dụng để nhóm các phương thức có liên quan với nhau với các phần thân rỗng:
// interface interface Animal { public void animalSound(); // interface method (does not have a body) public void run(); // interface method (does not have a body) } Để truy cập các phương thức giao diện, giao diện phải được “triển khai” (giống như kế thừa) bởi một lớp khác với implements từ khóa (thay vì extends). Phần thân của phương thức giao diện được cung cấp bởi lớp “hiện thực”:
// Interface interface Animal { public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) } // Pig "implements" the Animal interface class Pig implements Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); } public void sleep() { // The body of sleep() is provided here System.out.println("Zzz"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } } abstractvà publicpublic, staticvàfinal1) Để đạt được tính bảo mật – ẩn một số chi tiết nhất định và chỉ hiển thị các chi tiết quan trọng của một đối tượng (giao diện).
2) Java không hỗ trợ “đa kế thừa” (một lớp chỉ có thể kế thừa từ một lớp cha). Tuy nhiên, nó có thể đạt được với các giao diện, vì lớp có thể triển khai nhiều giao diện. Lưu ý: Để triển khai nhiều giao diện, hãy phân tách chúng bằng dấu phẩy (xem ví dụ bên dưới).
Để triển khai nhiều giao diện, hãy phân tách chúng bằng dấu phẩy:
interface FirstInterface { public void myMethod(); // interface method } interface SecondInterface { public void myOtherMethod(); // interface method } class DemoClass implements FirstInterface, SecondInterface { public void myMethod() { System.out.println("Some text.."); } public void myOtherMethod() { System.out.println("Some other text..."); } } class Main { public static void main(String[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); } } Lượt xem : 218
This is excellent news!
Haven't seen the build yet, I'll look now.
Checking the build now