Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java define a explicit package-private modifier [closed]

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;
like image 354
user7294900 Avatar asked Oct 29 '22 03:10

user7294900


1 Answers

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.

like image 107
Kartik Avatar answered Nov 15 '22 05:11

Kartik