ใน Java abstraction ทำได้ด้วย Abstract classes และ interfaces ทั้งคู่มี abstract methods ที่ child/implementing class ต้อง implement
| ลำดับ | หัวข้อ | Abstract Class | Interface |
|---|---|---|---|
| 1 | Supported Methods | มี abstract และ concrete methods ได้ | มีแค่ abstract methods (Java 8+ มี default/static ได้) |
| 2 | Multiple Inheritance | ไม่รองรับ | รองรับ |
| 3 | Supported Variables | final, non-final, static, non-static | static และ final เท่านั้น |
| 4 | Implementation | implement interface ได้ | implement interface ไม่ได้ (extend ได้) |
| 5 | Keyword | abstract | interface |
| 6 | Inheritance | extends class และ implements interface | extends interface เท่านั้น |
| 7 | Inheritance (be inherited) | extends abstract class | implements interface |
| 8 | Access Modifiers | private, public, protected, default | public เท่านั้น |
ตัวอย่าง
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");
}
}
ผลลัพธ์
Tiger eats Lion eats