为什么Java受到“保护”?保护程度低于默认值? [英] Why is Java's "protected" less protected than default?

查看:80
本文介绍了为什么Java受到“保护”?保护程度低于默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们有四个访问说明符: public protected ,package-private(默认)和私人。这是 已知

In Java, we have four access specifiers: public, protected, package-private (default), and private. This is well known and not an issue for me.

我的问题是关于受保护的$code的命名。如此处的表所示,为字段提供了默认的package-private访问说明,以防止使用包外部的子类它,但应用 protected 关键字实际上并不能对其进行保护–相反,它向任何包的子类开放。

My question is with regard to the naming of protected. As shown in the table here, giving a field the default access specifier of package-private prevents subclasses outside of the package from using it, but applying the keyword protected doesn't actually protect it – on the contrary, it opens it up to subclasses of any package.

所以,为什么不保护 东西为什么它比完全没有修饰符的限制要

So, why doesn't protected protect things; why is it less restrictive than no modifier at all?

推荐答案

如果我们接受那些是应当存在四个访问级别(私有,程序包私有,程序包私有加上子类和公共),并且当您未指定其他内容时,我们接受程序包私有应为默认访问级别,那么这个问题变成:为什么包私有+子类称为受保护的?答案是它从C ++借用/继承了该术语(C ++没有包的概念,但使用 protected 表示私有加-subclasses)。

If we accept that those are the four access levels that should exist (private, package-private, package-private-plus-subclasses, and public), and we accept that package-private should be the default access level when you don't specify something else, then this question becomes: "why is package-private-plus-subclasses called protected?" And the answer to that is that it borrowed/inherited the term from C++ (which doesn't have a concept of "packages", but uses protected to mean "private-plus-subclasses").

(我将这个答案发布为社区Wiki,以鼓励其他人添加它,因为我猜测故事的内容比而且,因为有人可能想添加一些理由,说明为什么这是应该存在的四个访问级别—例如,为什么我们有package-private-plus-subclasss但没有private-plus-subclasss—为什么package-private应该是默认值。)

(I'm posting this answer as community wiki to encourage others to add to it, since I'm guessing that there's more to the story than just this. Also, because someone may want to add some justification of why these are the four access levels that should exist — e.g., why we have package-private-plus-subclasses but no private-plus-subclasses — and of why package-private should be the default.)

这篇关于为什么Java受到“保护”?保护程度低于默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆