Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I override a protected method with public method?

Tags:

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?

like image 965
Monstieur Avatar asked Apr 15 '14 10:04

Monstieur


People also ask

Can you give public access modifier where you are overriding a protected method?

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.

What methods are impossible to override?

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.

Can you override a protected method PHP?

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.

Can we override public method to private in Java?

You cannot override a private or static method in Java.


1 Answers

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.
like image 62
Harmlezz Avatar answered Oct 24 '22 10:10

Harmlezz