Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ทำไม Java Class ไม่สามารถเป็น Abstract และ Final พร้อมกันได้?

เพราะ Abstract และ Final ขัดแย้งกันโดยตรงในระดับ Class

Abstract Class

  • หมายถึง: ต้องถูก Extend (สืบทอด) เพื่อให้ Implement Abstract Methods
  • ไม่สามารถ Instantiate (new) ได้โดยตรง
  • วัตถุประสงค์: เป็น Template/Base Class

Final Class

  • หมายถึง: ห้ามถูก Extend (สืบทอด) ไม่สามารถเป็น Parent Class ได้
  • สามารถ Instantiate ได้ปกติ
  • วัตถุประสงค์: ป้องกันการแก้ไขพฤติกรรมผ่าน Inheritance (Immutable, Security)

ความขัดแย้ง

Modifier ข้อกำหนด
abstract ต้องมี Subclass (ต้อง Extend)
final ห้ามมี Subclass (ห้าม Extend)

ถ้า Class เป็น abstract final -> ต้อง Extend (จาก abstract) แต่ห้าม Extend (จาก final) -> Logic Contradiction

ตัวอย่าง Error

public final abstract class Example { // Compile Error
    public void sample() {}
}

Compile Error

Example.java:1: error: illegal combination of modifiers: abstract and final
public final abstract class Example {
       ^

กรณี Method Level (แตกต่างจาก Class)

ระดับ Method: abstract และ final ก็ห้ามรวมกันได้เหมือนกัน

  • abstract method = ต้อง Override
  • final method = ห้าม Override
  • ขัดแย้งกัน -> illegal combination of modifiers

สรุป

  • Class Level: abstract = ต้อง Extend, final = ห้าม Extend -> ขัดแย้ง -> ห้ามรวมกัน
  • Method Level: abstract = ต้อง Override, final = ห้าม Override -> ขัดแย้ง -> ห้ามรวมกัน
  • Design: Abstract Class ใช้สำหรับ Extension, Final Class ใช้สำหรับ Prevention of Extension