The Java compiler doesn't complain when I override a protected
method with a public
method. What's really happening here? Is it overriding or hiding the parent method since the parent method has lower visibility?
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.
Non-virtual or static methods cannot be overridden. The overridden base method must be virtual, abstract, or override. In addition to the modifiers that are used for method overriding, C# allows the hiding of an inherited property or method.
The problem isn't that you cannot override the protected method, it's that you are calling a protected method from outside of the class. After the class is instantiated, you can call a public method which in turn could call get_name() and you will see that the code will work as expected.
You cannot override a private or static method in Java.
A sub-class can always widen the access modifier, because it is still a valid substitution for the super-class. From the Java specification about Requirements in Overriding and Hiding:
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
- If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
- If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
- If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
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