If we change the access specifier under function overriding what will happen? Is this allowed?

Yes, it is allowed to change the access specifier when overriding a method in Java, but there are specific rules that must be followed.

Explanation

  1. Access Specifier Rules:
  2. Explanation: When you override a method in a subclass, you can change the access specifier of the overridden method, but the new access specifier must be less restrictive or the same as the one in the superclass.
  3. Allowed Changes:
    • You can make the access specifier more accessible.
    • For example, you can override a protected method in the superclass with a public method in the subclass.
  4. Not Allowed:

    • You cannot make the access specifier more restrictive.
    • For example, you cannot override a public method in the superclass with a protected or private method in the subclass.
  5. Examples:

  6. Allowed:

```java

class Parent {

protected void show() {

System.out.println("Parent show()");

}

}

class Child extends Parent {

@Override

public void show() { // Changed from protected to public

System.out.println("Child show()");

}

}

```
3. Not Allowed:

```java

class Parent {

public void display() {

System.out.println("Parent display()");

}

}

class Child extends Parent {

@Override

protected void display() { // Compilation error: Cannot reduce the visibility of the inherited method

System.out.println("Child display()");

}

}

```

  1. Rationale:
  2. Explanation: The reason for this rule is to ensure that the overridden method is still accessible wherever the original method was accessible. Reducing the access level could lead to situations where code that was able to call the method in the superclass would be unable to call it on an object of the subclass.

Summary

  • Allowed: You can increase the access level when overriding a method (e.g., from protected to public).
  • Not Allowed: You cannot decrease the access level (e.g., from public to protected or private).

Follow-up Question

  1. What happens if you try to reduce the access level of an overridden method?
  2. Answer: The code will not compile, and the compiler will throw an error indicating that you cannot reduce the visibility of the inherited method.