Can we override a protected method in Java?

Aug 22, 2021 · 1 min read

protected means access to the method is restricted to the same package or by inheritance. So the answer is, yes, protected methods can be overridden by a subclass in any package. By contrast, package (default) scoped methods are not visible even to subclasses that are in a different package.

In general, the access specifiers for overriding methods allow more, but not less, access than the overridden method. This is because implementors of the subclass know what they are doing and can choose to give more access. Thus, when overriding protected method, the subclass can choose to override it with protected or public access modifier, but no a weaker one such as private or default.

Example

Object is the superclass of all classes in Java and sits at the top of hierarchy. It has a protected method called Object.clone.

protected Object clone(); // Creates and returns a copy of this object.

In the example below, let’s override the clone() method and make it public. By making it public, we allow the clone method to be called on Employee objects from anywhere.

package is;

public class Employee implements Cloneable {
    private Name name = new Name();
    private int employeeNumber;

    @Override
    public Object clone() throws CloneNotSupportedException {
        System.out.println("cloning employee");
        return super.clone();
    }
}

Notes:

  • You cannot declare a class as protected. Only the methods or fields within a class can have this access modifier.
#question #java

You May Also Enjoy


If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!