javaaccess-modifiersaccess-levels

Java define a explicit package-private modifier


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;

Solution

  • 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.