In Iava, Can we change the scope of the overridden method in the subclass ?
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:
private
default
(no modifier)protected
public
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.
protected
to public
).protected
to private
).