Java定义一个显式的package-private修饰符 [英] Java define a explicit package-private modifier

查看:343
本文介绍了Java定义一个显式的package-private修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,Java具有访问级别 package-private 通过不添加任何显式修饰符来实现的.

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.

编辑

您可以使用Lombok的 @PackagePrivate

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

用于指示带注释的实体具有包私有访问级别的明确意图.当前由FieldDefaults和Value使用,以避免使它成为公共字段,受保护字段或私有字段之一.

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;

推荐答案

我认为

如果默认值为

public,因为您可能会错过指定修饰符和本打算是私有的代码段,或者世界上可能会访问的某些代码.此外,这可能与OOP的核心概念之一-封装.

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,因为通常您希望与其他类进行交互,而不是将所有内容都写在一个类中.

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

protected,因为我希望(个人观点)文件夹(包)中的内容可在文件夹内访问,而不是位于完全不同的目录中的类(子类)中.

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.

如果我要再做一次,我将选择package-private作为默认设置,因为如果某些东西在一起(在同一包中),则可能是它们应该能够互相交谈.

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.

这篇关于Java定义一个显式的package-private修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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