Java Method Overriding: Scope Change Rules Explained

Answered using GPT-4o-mini by Java Q&A Hub

Question:

In Iava, Can we change the scope of the overridden method in the subclass ?

Answer:

In Java, when you override a method in a subclass, you cannot change the visibility (scope) of that method to be more restrictive than it is in the superclass. However, you can make the overridden method more accessible (i.e., you can change it to a less restrictive access modifier).

Here are the access modifiers in Java, from most restrictive to least restrictive:

  1. private
  2. default (no modifier)
  3. protected
  4. public

Example:

class SuperClass {
    protected void display() {
        System.out.println("Display from SuperClass");
    }
}

class SubClass extends SuperClass {
    // This is allowed: changing from protected to public
    public void display() {
        System.out.println("Display from SubClass");
    }

    // This is NOT allowed: changing from protected to private
    // private void display() {
    //     System.out.println("Display from SubClass");
    // }
}

In the example above, the display method in SubClass can be declared as public, but it cannot be declared as private. If you try to make it private, you will get a compile-time error.

Summary:

  • You can increase the visibility of an overridden method (e.g., from protected to public).
  • You cannot decrease the visibility of an overridden method (e.g., from protected to private).