Trong Java, trừu tượng hóa đạt được bằng Abstract class và Interface. Cả hai chứa phương thức trừu tượng mà lớp con hoặc lớp triển khai phải implement. Dưới đây là những khác biệt quan trọng giữa abstract class và interface.
| Thứ tự | Khóa | Abstract Class | Interface |
|---|---|---|---|
| 1 | Phương thức hỗ trợ | Abstract class có thể có cả abstract và concrete methods. | Interface chỉ có abstract methods. Từ Java 8, có default và static methods. |
| 2 | Kế thừa đa dạng | Không hỗ trợ multiple inheritance. | Interface hỗ trợ multiple inheritance. |
| 3 | Biến hỗ trợ | Hỗ trợ final, non-final, static, non-static. | Chỉ cho phép static và final. |
| 4 | Triển khai | Abstract class có thể implements interface. | Interface không thể implements interface, chỉ extends interface. |
| 5 | Từ khóa | Abstract class khai báo bằng abstract keyword. | Interface khai báo bằng interface keyword. |
| 6 | Kế thừa | Abstract class có thể extends class khác và implements interface. | Interface chỉ có thể extends interface. |
| 7 | Kế thừa (tiếp) | Abstract class có thể được extends. | Interface chỉ có thể được implements. |
| 8 | Truy cập | Abstract class có thể có members private, public. | Interface chỉ có thể có public members. |
Ví dụ Abstract Class vs Interface
JavaTester.java
public class JavaTester {
public static void main(String args[]) {
Animal tiger = new Tiger();
tiger.eat();
Cat lion = new Lion();
lion.eat();
}
}
interface Animal {
public void eat();
}
class Tiger implements Animal {
public void eat() {
System.out.println("Tiger eats");
}
}
abstract class Cat {
abstract public void eat();
}
class Lion extends Cat {
public void eat() {
System.out.println("Lion eats");
}
}
Kết quả
Tiger eats Lion eats