คำตอบคือ ไม่ได้ การ 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)- สืบทอดมาจาก Supersample(int, float)- เมธอดใหม่ของ Subclass
obj.sample(20, 20) ค่าคงที่ 20 เป็น int จึง Match กับเมธอดของ Super class
กฎ Overriding ที่ต้องปฏิบัติ
- ชื่อเมธอดเหมือนกัน
- Parameter List เหมือนกัน (จำนวน, ชนิด, ลำดับ)
- Return Type เหมือนกัน (หรือเป็น Covariant Return Type - Subclass ของ Return Type เดิม)
- Access Modifier ต้องไม่เข้มงวดกว่า (public > protected > default > private)
- Checked Exception ต้องไม่โยน Supertype (ตามบทความก่อนหน้า)