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

สามารถเปลี่ยน Method Signature ขณะ Overriding ใน Java ได้หรือไม่?

คำตอบคือ ไม่ได้ การ Override ต้องมี ชื่อ เมธอด, พารามิเตอร์ (Parameter Types และ Order), และ Return Type เหมือนกันทุกประการ หากเปลี่ยน Signature จะถูกมองว่าเป็นเมธอดใหม่ (Overloading) ไม่ใช่ Overriding

ตัวอย่างที่ไม่ใช่ Overriding

class Super {
    void sample(int a, int b) {
        System.out.println("Method of the Super class");
    }
}

public class MethodOverriding extends Super {
    // เปลี่ยนพารามิเตอร์ int b -> float b => เป็น Overloading ไม่ใช่ Overriding
    void sample(int a, float b) {
        System.out.println("Method of the Sub class");
    }

    public static void main(String args[]) {
        MethodOverriding obj = new MethodOverriding();
        obj.sample(20, 20); // เรียกเมธอดของ Super class (int, int)
    }
}

ผลลัพธ์

Method of the Super class

เหตุผล

เมื่อ Signature ต่างกัน Java จะถือว่าเป็นเมธอดคนละตัว (Overloading) Subclass จึงมีทั้งสองเมธอด:

  • sample(int, int) - สืบทอดมาจาก Super
  • sample(int, float) - เมธอดใหม่ของ Subclass
เมื่อเรียก obj.sample(20, 20) ค่าคงที่ 20 เป็น int จึง Match กับเมธอดของ Super class

กฎ Overriding ที่ต้องปฏิบัติ

  1. ชื่อเมธอดเหมือนกัน
  2. Parameter List เหมือนกัน (จำนวน, ชนิด, ลำดับ)
  3. Return Type เหมือนกัน (หรือเป็น Covariant Return Type - Subclass ของ Return Type เดิม)
  4. Access Modifier ต้องไม่เข้มงวดกว่า (public > protected > default > private)
  5. Checked Exception ต้องไม่โยน Supertype (ตามบทความก่อนหน้า)