Câu trả lời: CÓ
Phương thức protected của lớp cha có thể override bởi lớp con. Quy tắc access modifier khi override:
- Modifier của subclass không được hẹp hơn (weaker) so với superclass.
protected→ có thể override thànhprotectedhoặcpublic.- Không thể override thành
default(package-private) hoặcprivate.
Ví dụ
class A {
protected void protectedMethod() {
System.out.println("Superclass protected method");
}
}
class B extends A {
@Override
protected void protectedMethod() { // hoặc public
System.out.println("Subclass protected method");
}
}
public class OverrideProtectedDemo {
public static void main(String[] args) {
B b = new B();
b.protectedMethod(); // Gọi version của subclass
}
}
Kết quả
Subclass protected method
Lưu ý: @Override annotation giúp compiler kiểm tra lỗi override (sai signature, modifier hẹp hơn...).