Can we override a protected method in Java?


Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.

Example

class A {
   protected void protectedMethod() {
      System.out.println("superclass protected method");
   }
}
class B extends A {
   protected void protectedMethod() {
      System.out.println("subclass protected method");
   }
}
public class Test {
   public static void main(String args[]) {
      B b = new B();
      b.protectedMethod();
   }
}

Output

subclass protected method

Updated on: 01-Dec-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements