4

在 Java 中,我们有四个访问说明符:publicprotected、 package-private (默认)和private. 这是众所周知 ,对我来说不是问题。

我的问题是关于protected. 如这里的表所示,为字段提供 package-private 的默认访问说明符可防止包外的子类使用它,但应用关键字protected实际上并不能保护它——相反,它会将其开放给任何包裹。

那么,为什么不protected保护东西呢?为什么它的限制比没有修饰符少?

4

3 回答 3

6

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").

(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.)

于 2013-03-25T23:00:45.377 回答
3

由于这是一个相当开放的问题,我将提供一些半相关的历史背景。在 Java 1.0 中有一个额外的访问修饰符,private protected。这是受保护的减去包访问权限。此修饰符令人困惑,实施不佳,并在 1.1 中删除。这有助于描绘包是逻辑模块化单元的画面,因此是默认的访问级别。

归根结底,这归结为对开发人员有意义的个人选择。每个人的想法都不一样,所以对我来说完全有意义的命名约定可能会让你非常困惑(反之亦然)。

于 2013-03-25T23:06:15.147 回答
1

受保护的比公开的更具限制性。这就是为什么它被称为它是什么。

我希望语言设计者将默认访问说明符命名为“包保护”,因为默认值对很多程序员来说非常混乱。我更赞成将保护作为默认值,或者根本没有默认值.

于 2013-03-25T22:59:57.403 回答