In Java, when I override a method the compiler flags off any attempt to narrow down the visibility as an error. For ex: I can't override a public method as protected, while I can override a protected method as public.
I am interested in knowing the design decision/thinking behind this rule.
Hence the rule is Overriding method should not decrease the scope of overridden method. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.
Method 1: Using a static method This is the first way of preventing method overriding in the child class. If you make any method static then it becomes a class method and not an object method and hence it is not allowed to be overridden as they are resolved at compilation time and overridden methods are resolved at runtime.
The rules are there so you don't lose the original throws declaration by widening the specificity, as the polymorphism means you can invoke the overriden method on the superclass. The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.
Overriding means redefining a behaviour (method) again in the child class which was already defined by its parent class but to do so overriding method in the child class must follow certain rules and guidelines. With respect to the method it overrides, the overriding method must follow following rules.
A subclass should always satisfy the contract of the superclass. See Liskov Substitution principle.
The visibility of methods is part of this contract. So anything publicly visible in the superclass should be public in the subclass as well.
Consider a class B
which inherits from A
. A.m()
is public. Now consider this code:
A obj = new B();
obj.m();
Should this call be allowed? Yes, it should, because obj
is an object of type A
! It is also an object of type B
, but that is not necessarily known to the one using the object.
Every object of type A
must adhere to the contract (interface) for A
. B
extends A
and must therefore also adhere to that contract.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With