[英]Why doesn't java allow to assign weaker access privileges to static methods in a child class?
I understand why java doesn't allow to set weaker access privileges for overridden methods, but why is it the same for static methods? 我理解为什么java不允许为重写方法设置较弱的访问权限,但为什么静态方法是相同的呢? I mean, these methods only hide each others, right?
我的意思是,这些方法只能隐藏对方,对吗? So what's the problem from the encapsulation point of view?
那么从封装的角度来看问题是什么?
PS PS
I know that there are 5 rules for hiding a method 我知道隐藏方法有5条规则
But after all, I don't get the idea from the encapsulation prospective 但毕竟,我从封装前景中得不到这个想法
Static methods have special access permissions that allow friend access to members within a instance. 静态方法具有特殊的访问权限,允许朋友访问实例中的成员。 For example, you could have a static method called
create
that creates a default instance of the class and directly modifies data within the instance without using instance properties or instance methods (just for a usage example, not necessarily a usage recommendation). 例如,您可以使用名为
create
的静态方法create
类的默认实例,并直接修改实例中的数据,而无需使用实例属性或实例方法(仅用于用法示例,不一定是用法建议)。
Because of this special access, lower access permissions to the static methods could allow you to create an object in a state that you could not otherwise use, or modify an object in an unpredictable and non-encapsulated way. 由于这种特殊访问,对静态方法的较低访问权限可以允许您创建一个您无法使用的状态的对象,或以不可预测和非封装的方式修改对象。
This is only a minor annoyance for most user-defined classes, but allowing this when sub-classing eg containers could expose serious undefined behavior problems. 对于大多数用户定义的类来说,这只是一个小麻烦,但是在对容器进行子类化时允许这样做可能会暴露严重的未定义行为问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.