Java – contrary to C, why can’t you reduce method visibility when overriding?
•
Java
See English answer > java, cannot reduce the visibility of the inherited method from object
abstract class A { protected void method() {} } class B extends A { private void method() {} } public class main{ public static void main(String []args) {} }
yes:
main.java:6: error: method() in B cannot override method() in A private void method() {} ^ attempting to assign weaker access privileges; was protected 1 error
Set the derived method to protected / private
Question: why does Java not allow you to further restrict access in subclasses? I contrast this with C, which has completely opposite rules
Solution
In Java, all methods are virtual by default (except private and static methods) Therefore, when using java to rewrite a method, it must use the definition in the class referenced by the object With this rule in Java, you can't reduce the visibility of the overridden method, just keep the same visibility or expand it
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码