Java define a explicit package-private modifier [closed]

眉间皱痕 提交于 2020-07-20 17:11:36

问题


Obviously Java has a Access level package-private which achieved by not adding any explicit modifier.

But isn't there a way to explicitly add this modifier? It's a bit confusing that we need to omit access level when we want to use member in package only.

If there's no way, why package private decided to be a default level?

For example if default level was public than we would more consciously define relevant access level.

This isn't duplicate of question of why use it, because I know why, I just don't know why it's define implicitly and can't be defined explicitly.

EDIT

You can define it explicitly by using Lombok's @PackagePrivate

Used to indicate the explicit intention for the annotated entity to have the package private access level. Currently used by FieldDefaults and Value to avoid having it make a field one of public, protected, or private.

@PackagePrivate String thanksLombok;

回答1:


In my opinion,

It would be bad if the default was

public because you could miss specifying the modifier and the piece of code that was intended to be private or something would be accessible to the world. Also, this might be against one of the OOP's core concepts - encapsulation.

private because generally you would want to interact with other classes instead of writing everything in one class.

protected because I would expect (personal opinion) things that are in a folder (package) to be accessible inside the folder and not in a class (child class) residing in some completely different directory.


If I were to do it again, I would choose package-private as the default because if some things are together (in the same package), the intention might be that they should be able to talk to each other.




回答2:


But isn't there a way to explicitly add this modifier?

No there isn't. (Short of modifying the Java language, which is highly unlikely for something like this.)

The rest of your question calls for opinion-based answers1 and is off topic.


1 - 1) We were not in the room ~25 years ago when the design decisions were made. 2) There is (AFAIK) no extant publicly available documentation for the original language design decisions. 3) The people who were in the room will have probably mostly forgotten, even if we could ask them. 4) Any attempt by your / me to "reverse engineer" the original thinking will be colored by ~25 years of hindsight.



来源:https://stackoverflow.com/questions/52620127/java-define-a-explicit-package-private-modifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!