Java中的公众,受保护,包裹私有和私人有什么区别?
在Java中,是否有明确的规则,即何时使用访问修饰符,即默认值(package private), public
,受保护
and private
private ,在制作 class
和接口
并处理继承时?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
官方教程可能对您有所使用。
❌:无法访问
The official tutorial may be of some use to you.
(same pkg)
(diff pkg)
public
protected
private
✔️: accessible
❌: not accessible
(警告:我不是Java程序员,我是Perl程序员。Perl没有正式的保护,这也许就是为什么我很好地理解问题了:)
私有
) >被声明的可以看到它。
私有包装
只有 package 才能使用它。这是Java中的默认值(有些人将其视为错误)。
受保护的
软件包私有 +可以通过子类或软件包成员看到。
公众
每个人都可以看到它。
已发布
在我控制的代码之外可见。 (虽然不是Java语法,但对于此讨论来说很重要)。
C ++定义了一个称为“朋友”的额外级别,您对此的了解越少。
您什么时候应该使用什么?整个想法是封装以隐藏信息。您想尽可能地隐藏用户如何完成某件事的细节。为什么?因为那样,您可以在以后更改它们,而不会破坏任何人的代码。这使您可以优化,重构,重新设计和修复错误,而不必担心有人在使用您刚刚大修的代码。
因此,经验法则是使事物只能使事情尽可能可见。从私有开始,只能根据需要添加更多的可见性。仅公开用户知道的必要条件,您将使您公开的每个细节都会重新设计系统。
如果您希望用户能够自定义行为,而不是将内部设置公开以使他们可以覆盖它们,那么将这些胆量推入对象并将该界面公开是一个更好的主意。这样,他们可以简单地插入一个新对象。例如,如果您正在编写CD播放器,并且想要“查找有关此CD的信息”有点可自定义,而不是公开这些方法,您将所有这些功能都放在其对象中,并将您的对象Getter/Setter公开。这样一来,暴露您的胆量就会促进良好的构图和分离,
我只是坚持使用“私人”和“公共”。许多OO语言只有它。 “受保护”可以方便,但这是一个作弊。一旦接口不仅仅是私有,它就不在您的控制之外,您必须查看其他人的代码才能找到用途。
这就是“已发布”的想法。更改接口(重构)要求您找到使用它的所有代码并将其更改。如果接口是私有的,那没问题。如果受到保护,则必须去查找所有子类。如果是公众,则必须去查找使用您的代码的所有代码。有时,例如,如果您正在使用用于内部使用的公司代码,那么仅界面是公开的,这无关紧要。您可以从公司存储库中获取所有代码。但是,如果“发布”界面,则使用该界面在您的控件之外使用它,则您是软管。您必须支持该接口或风险破坏代码。甚至受保护的界面也可以被认为已发布(这就是为什么我不为受保护的原因)。
许多语言认为公共/保护/私人的层次结构性质过于限制,并且与现实不符。为此,有一个特质类的概念,但这是另一个节目。
(Caveat: I am not a Java programmer, I am a Perl programmer. Perl has no formal protections which is perhaps why I understand the problem so well :) )
Private
Like you'd think, only the class in which it is declared can see it.
Package Private
It can only be seen and used by the package in which it was declared. This is the default in Java (which some see as a mistake).
Protected
Package Private + can be seen by subclasses or package members.
Public
Everyone can see it.
Published
Visible outside the code I control. (While not Java syntax, it is important for this discussion).
C++ defines an additional level called "friend" and the less you know about that the better.
When should you use what? The whole idea is encapsulation to hide information. As much as possible you want to hide the detail of how something is done from your users. Why? Because then you can change them later and not break anybody's code. This lets you optimize, refactor, redesign, and fix bugs without worrying that someone was using that code you just overhauled.
So, the rule of thumb is to make things only as visible as they have to be. Start with private and only add more visibility as needed. Only make public that which is necessary for the user to know, every detail you make public cramps your ability to redesign the system.
If you want users to be able to customize behaviors, rather than making internals public so they can override them, it's often a better idea to shove those guts into an object and make that interface public. That way they can simply plug in a new object. For example, if you were writing a CD player and wanted the "go find info about this CD" bit customizable, rather than make those methods public you'd put all that functionality into its object and make just your object getter/setter public. In this way being stingy about exposing your guts encourages good composition and separation of concerns
I stick with just "private" and "public". Many OO languages just have that. "Protected" can be handy, but it's a cheat. Once an interface is more than private it's outside of your control and you have to go looking in other people's code to find uses.
This is where the idea of "published" comes in. Changing an interface (refactoring it) requires that you find all the code which is using it and change that, too. If the interface is private, well no problem. If it's protected you have to go find all your subclasses. If it's public you have to go find all the code which uses your code. Sometimes this is possible, for example, if you're working on corporate code that's for internal use only it doesn't matter if an interface is public. You can grab all the code out of the corporate repository. But if an interface is "published", if there is code using it outside your control, then you're hosed. You must support that interface or risk breaking code. Even protected interfaces can be considered published (which is why I don't bother with protected).
Many languages find the hierarchical nature of public/protected/private to be too limiting and not in line with reality. To that end, there is the concept of a trait class, but that's another show.
这是表格的更好版本,还包括一个用于模块的列。
说明
a 私有成员(
i
)是仅在同一类中访问被声明。的成员无访问修饰符(
j
)仅在同一软件包中的类中访问。a 受保护成员(
k
)在其他软件包中的子类中的所有类中的所有类中都可以访问。。
a public 成员(
l
)均可访问所有类(除非它位于a 模块不会导出其声明的软件包。)。
选择哪种修饰符?
访问修饰符是一种工具,可帮助您防止意外破坏封装(*)。问问自己,您是否打算将成员成为班级内部,包装,班级层次结构的内部内容,并相应地选择访问级别。
示例:
长internallcounter
可能是私人的,因为它是可变的,并且是实现细节。void beforerender()
方法在渲染前称为``渲染'',并且应保护子类中的钩子。void savegame(file dst)
从GUI代码调用的方法应为公共。(*)什么是封装?
Here's a better version of the table, that also includes a column for modules.
Explanations
A private member (
i
) is only accessible within the same class as it is declared.A member with no access modifier (
j
) is only accessible within classes in the same package.A protected member (
k
) is accessible within all classes in the same package and within subclasses in other packages.A public member (
l
) is accessible to all classes (unless it resides in a module that does not export the package it is declared in).Which modifier to choose?
Access modifiers is a tool to help you to prevent accidentally breaking encapsulation(*). Ask yourself if you intend the member to be something that's internal to the class, package, class hierarchy or not internal at all, and choose access level accordingly.
Examples:
long internalCounter
should probably be private since it's mutable and an implementation detail.void beforeRender()
method called right before rendering and used as a hook in subclasses should be protected.void saveGame(File dst)
method which is called from the GUI code should be public.(*) What is Encapsulation exactly?
简单的规则。首先宣布一切私人。然后随着需求的出现和设计而朝着公众迈进。
暴露成员时,问自己是否正在公开表示的选择或抽象选择。首先是您要避免的事情,因为它会引入太多对实际表示形式而不是可观察到的行为的依赖性。
作为一般规则,我试图避免通过子分类来避免覆盖方法实现;搞砸逻辑太容易了。如果您打算覆盖抽象的方法,请声明抽象保护方法。
另外,在覆盖时,请使用@Override注释,以防止重构时发生折断。
Easy rule. Start with declaring everything private. And then progress towards the public as the needs arise and design warrants it.
When exposing members ask yourself if you are exposing representation choices or abstraction choices. The first is something you want to avoid as it will introduce too many dependencies on the actual representation rather than on its observable behavior.
As a general rule I try to avoid overriding method implementations by subclassing; it's too easy to screw up the logic. Declare abstract protected methods if you intend for it to be overridden.
Also, use the @Override annotation when overriding to keep things from breaking when you refactor.
实际上,它比简单的网格显示要复杂一些。网格告诉您是否允许访问,但是究竟是什么构成访问权限?此外,访问级别以复杂的方式与嵌套类和继承相互作用。
“默认”访问(由缺少关键字指定)也称为 package-package-package-private < /strong> 。例外:在接口中,没有修改器意味着公共访问;禁止公众以外的其他修饰符。枚举常数始终是公开的。
摘要
是否允许使用此访问说明符对成员的访问?
私有
:仅当成员与调用代码同一类中定义。受保护
:相同的软件包,或者如果在包含调用代码的类的超级类别中定义了成员。public
:是。访问说明符适用于
本地变量和正式参数无法访问访问说明符。由于根据范围的规则,它们本质上无法访问外部,因此实际上是私人的。
对于顶部范围中的课程,仅允许
public
和软件包私有化。这种设计选择大概是因为受保护的
和私有
在软件包级别上是多余的(没有包装的继承)。类成员(构造函数,方法和静态成员函数,嵌套类)上所有访问说明符都是可能的。
相关: Java类可访问性
订购访问
访问说明器可以严格订购
含义
public
提供了最多的访问权限,私有
至少。私人成员可能的任何参考也适用于软件包私人会员;对软件包私有化成员的任何引用对受保护的成员有效,依此类推。 中访问受保护的会员是错误的。
private [this]
。)。
您还必须考虑 nested 示波器,例如内部类 复杂性的一个例子是内部类有成员,他们自己可以使用访问修饰符。因此,您可以与公共成员一起拥有一个私人内部班级;可以访问成员吗? (请参见下文。)一般规则是查看范围并递归思考,以查看是否可以访问每个级别。
但是,这很复杂,并且有关全部详细信息,咨询Java语言规范。 (是的,过去有编译器的错误。)
为了考虑这些相互作用的方式,请考虑此示例。可以“泄漏”私人内部类;这通常是一个警告:
编译器输出:
一些相关问题:
It's actually a bit more complicated than a simple grid shows. The grid tells you whether an access is allowed, but what exactly constitutes an access? Also, access levels interact with nested classes and inheritance in complex ways.
The "default" access (specified by the absence of a keyword) is also called package-private. Exception: in an interface, no modifier means public access; modifiers other than public are forbidden. Enum constants are always public.
Summary
Is an access to a member with this access specifier allowed?
private
: Only if member is defined within the same class as calling code.protected
: Same package, or if member is defined in a superclass of the class containing the calling code.public
: Yes.What access specifiers apply to
Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.
For classes in the top scope, only
public
and package-private are permitted. This design choice is presumably becauseprotected
andprivate
would be redundant at the package level (there is no inheritance of packages).All the access specifiers are possible on class members (constructors, methods and static member functions, nested classes).
Related: Java Class Accessibility
Order
The access specifiers can be strictly ordered
meaning that
public
provides the most access,private
the least. Any reference possible on a private member is also valid for a package-private member; any reference to a package-private member is valid on a protected member, and so on. (Giving access to protected members to other classes in the same package was considered a mistake.)Notes
private[this]
.)Inner classes
You also have to consider nested scopes, such as inner classes. An example of the complexity is that inner classes have members, which themselves can take access modifiers. So you can have a private inner class with a public member; can the member be accessed? (See below.) The general rule is to look at scope and think recursively to see whether you can access each level.
However, this is quite complicated, and for full details, consult the Java Language Specification. (Yes, there have been compiler bugs in the past.)
For a taste of how these interact, consider this example. It is possible to "leak" private inner classes; this is usually a warning:
Compiler output:
Some related questions:
根据经验法则:
私有
:类范围。默认值
(或package-Provate
):软件包范围。保护
:软件包范围 +儿童
(如软件包,但我们可以从不同的软件包子中进行子类)。受保护的修饰符始终保持“亲子”关系。public
:无处不在。结果,如果我们将访问权利划分为三个权利:
然后我们有一个简单的表:
As a rule of thumb:
private
: class scope.default
(orpackage-private
): package scope.protected
:package scope + child
(like package, but we can subclass it from different packages). The protected modifier always keeps the "parent-child" relationship.public
: everywhere.As a result, if we divide access right into three rights:
then we have this simple table:
在非常简短的
公共
中:可从任何地方访问。受保护
:可通过同一软件包的类和任何软件包中的子类访问。私有
:仅在同一类中访问。In very short
public
: accessible from everywhere.protected
: accessible by the classes of the same package and the subclasses residing in any package.private
: accessible within the same class only.Java中最误解的访问修饰符是
受保护
。我们知道它类似于默认修饰符,一个例外,子类可以看到它。但是如何?这是一个示例,希望能阐明混乱:假设我们有2个课程;
父亲
和son
,每个>在其自己的软件包中:让我们添加一个受保护的方法
foo()
>。方法
foo()
可以在4个上下文中调用:在同一软件包中的一类内部定义
foo()
在一个子类内,在当前实例上通过
此
或super
:在引用的类型是同一类的引用上:
在引用其类型是父类的引用上,它是
foo()
定义的软件包(auth> autherpackage
)[这可以包含在上下文中。 1]:以下情况无效。
在引用其类型为父类的引用上,它是 exter
foo()
定义的软件包(auth> autherpackage
):一个子类包装中的非群典(子类从其父母那里继承了受保护的成员,它使其成为非群体的私人):
The most misunderstood access modifier in Java is
protected
. We know that it's similar to the default modifier with one exception in which subclasses can see it. But how? Here is an example which hopefully clarifies the confusion:Assume that we have 2 classes;
Father
andSon
, each in its own package:Let's add a protected method
foo()
toFather
.The method
foo()
can be called in 4 contexts:Inside a class that is located in the same package where
foo()
is defined (fatherpackage
):Inside a subclass, on the current instance via
this
orsuper
:On an reference whose type is the same class:
On an reference whose type is the parent class and it is inside the package where
foo()
is defined (fatherpackage
) [This can be included inside context no. 1]:The following situations are not valid.
On an reference whose type is the parent class and it is outside the package where
foo()
is defined (fatherpackage
):A non-subclass inside a package of a subclass (A subclass inherits the protected members from its parent, and it makes them private to non-subclasses):
private
方法,变量和构造函数只能在声明的类本身中访问私有。
private访问修改器大多数限制性访问级别。类和界面不能私有。
注释
,如果班级中存在公共getter方法,则可以在类外访问私有的变量。
在超类中声明的变量,方法和构造函数只能由其他软件包中的子类或受保护成员类的软件包中的任何类访问。
受保护的
不能将受保护的访问修饰符应用于类和接口。
方法,可以声明字段受到保护,但是方法但是方法界面中的字段不能被
声明
。尝试使用它的非相关类。
public
可以从任何其他类访问公共的类,方法,构造函数,界面等。
因此,在公共类中声明的字段,方法,块可以是从属于Java Universe的任何类访问。
但是,如果我们要访问的公共类是在其他软件包中导入。
由于类继承,所有类的公共方法和变量均由其子类继承。
默认-no关键字:
默认访问修改器表示我们没有明确声明同一
在同一软件包中的任何其他类都可以使用任何访问控制修饰符的变量或方法。界面中的字段是隐式的公共静态最终最终的,默认接口中的方法是公开的。
note
我们不能覆盖静态字段。如果您尝试尝试要覆盖它不会显示任何错误
但这不起作用,除了我们之外。
相关答案
href =“ http://docs.oracle.com/javase/tutorial/java/java/javaoo/accesscontrol.html” rel =“ noreferrer”> http://docs.oracle.com/javase/javase/tutorial/tutorial/java/java/java/java/javaoo/accessconcescontrol-accontrol .html
http://www.tutorialspoint.com/java/java/java_access_modifiers.htm >
Private
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Note
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
Protected
The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Note
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
Public
A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
Default -No keyword:
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
Note
We cannot Override the Static fields.if you try to override it does not show any error
but it doesnot work what we except.
Related Answers
References links
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://www.tutorialspoint.com/java/java_access_modifiers.htm
java访问修饰符
访问修饰符可用于
class
, field [of] ,方法
。尝试访问,子类或覆盖此问题。字段
或方法
是通过class
。class
(子类)访问修饰符可以是任何。方法
(覆盖)访问修饰符应为相同或展开顶级类(第一级范围)可以是
public
和默认
。 [关于]嵌套类
>软件包不申请软件包层次结构[swift访问访问修饰符]
Java access modifiers
Access modifier can be applicable for
class
,field
[About],method
. Try to access, subclass or override this.field
ormethod
is through aclass
.class
(subclass) access modifier can be any.method
(override) access modifier should be the same or expand itTop level class(first level scope) can be
public
anddefault
.Nested class
[About] can have any of thempackage
is not applying for package hierarchy[Swift access modifiers]
差异可以在已经提供的链接中找到,但是使用哪个链接通常取决于“最少知识的原则”。仅允许所需的知名度最低。
The difference can be found in the links already provided but which one to use usually comes down to the "Principle of Least Knowledge". Only allow the least visibility that is needed.
私人:仅访问类
默认值(无修饰符):有限的访问类别和软件包
受保护:有限的访问类,软件包和子类(内部和外部包)
public :可以访问班级,软件包(ALL)和子类...简而言之。
Private: Limited access to class only
Default (no modifier): Limited access to class and package
Protected: Limited access to class, package and subclasses (both inside and outside package)
Public: Accessible to class, package (all), and subclasses... In short, everywhere.
访问修饰符有多个级别限制访问。
public:基本上很简单,无论是否在同一包中,您都可以从任何类中访问。
要访问如果您在同一软件包中,则可以直接访问,但是如果您在另一个软件包中,则可以创建类的对象。
默认值:可以从任何类别的软件包中访问相同的软件包。
要访问您可以创建类的对象。但是您无法在包装外访问此变量。
受保护:您可以在同一软件包中访问变量以及任何其他软件包中的子类。
因此,基本上是默认 +继承行为。
要访问基类中定义的受保护字段,您可以创建子类的对象。
私有:可以在同一类中访问。
在非静态方法中,您可以直接访问此参考(也在构造函数中),但要访问静态方法,则需要创建类的对象。
Access modifiers are there to restrict access at several levels.
Public: It is basically as simple as you can access from any class whether that is in same package or not.
To access if you are in same package you can access directly, but if you are in another package then you can create an object of the class.
Default: It is accessible in the same package from any of the class of package.
To access you can create an object of the class. But you can not access this variable outside of the package.
Protected: you can access variables in same package as well as subclass in any other package.
so basically it is default + Inherited behavior.
To access protected field defined in base class you can create object of child class.
Private: it can be access in same class.
In non-static methods you can access directly because of this reference (also in constructors)but to access in static methods you need to create object of the class.
Java中的访问修饰符。
Java访问修饰符用于在Java中提供访问控制。
1。默认值:
仅在同一软件包中的类可访问。
例如,
此访问比公共和受保护更受限制,但比私人限制更少。
2。公共
可以从任何地方访问。 (全局访问)
例如,
3。私人
仅在同一类内访问。
如果您尝试访问另一个类中的私人会员,则会丢弃编译错误。例如,
4。受保护
仅在同一软件包中的类中访问
,例如
Access modifiers in Java.
Java access modifiers are used to provide access control in Java.
1. Default:
Accessible to the classes in the same package only.
For example,
This access is more restricted than public and protected, but less restricted than private.
2. Public
Can be accessed from anywhere. (Global Access)
For example,
3. Private
Accessible only inside the same class.
If you try to access private members on one class in another will throw compile error. For example,
4. Protected
Accessible only to the classes in the same package and to the subclasses
For example,
包裹可见。默认值。不需要修饰符。
仅对班级可见(私有)。
可见世界( public )。
包装和所有子类可见(受保护)。
可以声明变量和方法,而无需任何调用符。默认示例:
私人访问修饰符 - 私有:
声明为私有的方法,变量和构造函数只能在声明的类本身中访问。私人访问修饰符是最严格的访问级别。类和界面不能私有。
如果班级中存在公共Getter方法,则可以在班级外访问私有的变量。
使用私有修饰符是对象封装自身并隐藏外界数据的主要方式。
示例:
公共访问修饰符 - 公共:
类,方法,构造函数,接口等。可以从任何其他类访问公共声明。因此,可以从属于Java宇宙的任何类中访问公共类中声明的字段,方法,块。
但是,如果我们试图访问的公共类是在另一个软件包中,则仍然需要进口公共类。
由于阶级继承,类的所有公共方法和变量均由其子类继承。
示例:
受保护的访问修饰符 - 受保护:
在超类中声明的变量,方法和构造函数只能由另一个软件包中的子类别或受保护成员类的软件包中的任何类中的子类访问。
受保护的访问修饰符不能应用于类和界面。方法,字段可以被声明保护,但是接口中的方法和字段不能被声明受保护。
受保护的访问使子类有机会使用助手方法或变量,同时防止非相关类尝试使用它。
Visible to the package. The default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Variables and methods can be declared without any modifiers that are called. Default examples:
Private access modifier - private:
Methods, variables and constructors that are declared private can only be accessed within the declared class itself. The private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
Examples:
Public access modifier - public:
A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java universe.
However, if the public class we are trying to access is in a different package, then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.
Example:
Protected access modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in another package or any class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
public - 可从应用程序中的任何地方访问。
默认值 - 可从软件包访问。
受保护的 - 可从其他软件包中的包装和子类访问。
以及
public - accessible from anywhere in the application.
default - accessible from package.
protected - accessible from package and sub-classes in other package.
as well
private - accessible from its class only.
此页面关于受保护的&amp&amp;默认访问修饰符
....
受保护:受保护的访问修饰符有点棘手,您可以说是默认访问修饰符的超集。就同一软件包中的访问而言,受保护的成员与默认成员相同。不同之处在于,受保护的成员也可以访问该类别的子类的子类,其中会员被宣布为出现父类的包装外。
但是,这些受保护的成员“仅通过继承才能在软件包之外访问”。即,您可以直接在其他软件包中访问其子类中的一个受保护的成员,就像子类本身中存在的成员一样。但是,通过使用父类的参考,该受保护的成员将无法在软件包外部的子类中访问。
...
This page writes well about the protected & default access modifier
....
Protected: Protected access modifier is the a little tricky and you can say is a superset of the default access modifier. Protected members are same as the default members as far as the access in the same package is concerned. The difference is that, the protected members are also accessible to the subclasses of the class in which the member is declared which are outside the package in which the parent class is present.
But these protected members are “accessible outside the package only through inheritance“. i.e you can access a protected member of a class in its subclass present in some other package directly as if the member is present in the subclass itself. But that protected member will not be accessible in the subclass outside the package by using parent class’s reference.
....
大卫的答案提供了每个访问修饰符的含义。至于何时使用,我建议公开所有班级和旨在外部用途(其API)以及其他所有私有所有班级的方法。
随着时间的流逝,您将对何时制作某些类包装私有化以及何时声明某些用于子类使用的方法的感觉。
David's answer provides the meaning of each access modifier. As for when to use each, I'd suggest making public all classes and the methods of each class that are meant for external use (its API), and everything else private.
Over time you'll develop a sense for when to make some classes package-private and when to declare certain methods protected for use in subclasses.
此图像将使您轻松了解公共,私人,受保护和默认访问修饰符之间的基本差异。当您不声明代码中的蚂蚁访问修饰符时,默认修饰符会自动进行。
This image will make you understand easily about the basic differences between public, private, protected and default access modifiers. The default modifier takes place automatically when you don't declare ant access modifiers in your code.
公共受保护的默认值和私人是访问修饰符。
它们是用于封装或隐藏和显示班级内容的内容。
私人在班上不可访问
默认值仅在软件包中访问。
在包装中受保护以及任何扩展它的类。
公众对所有人开放。
通常,会员变量是私人定义的,但成员方法是公开的。
Public Protected Default and private are access modifiers.
They are meant for encapsulation, or hiding and showing contents of the class.
Private is not accessible outside the class
Default is accessible only in the package.
Protected in package as well as any class which extends it.
Public is open for all.
Normally, member variables are defined private, but member methods are public.
注意:这只是接受答案的补充。
这与Java 访问修饰符。
来自 java访问修饰符:
来自教程:
Note: This is just a supplement for the accepted answer.
This is related to Java Access Modifiers.
From Java Access Modifiers:
From Controlling Access to Members of a Class tutorials:
通常,我意识到,记住任何语言的基本概念都可以通过创建现实世界的类比来实现。这是我的类比,用于了解Java的访问修饰符:
让我们假设您是大学的学生,并且有一个朋友在周末要来拜访您。假设在校园中间有一个大学创始人的大雕像。
当您将他带到校园时,您和您的朋友所看到的第一件事就是这个雕像。这意味着,任何在校园里行走的人都可以未经大学许可来看雕像。这使得雕像成为公共。
接下来,您想带您的朋友去宿舍,但为此,您需要将他注册为访客。这意味着他获得了进入校园各种建筑物的访问通行证(与您相同)。这将使他的访问卡为受保护。
您的朋友想登录校园wifi,但没有任何凭据。他可以上网的唯一方法是与他分享登录名。 (请记住,每个上大学的学生也都拥有这些登录证书)。这将使您的登录凭据为没有修改器。
最后,您的朋友想阅读您在网站上发布的学期的进度报告。但是,每个学生都有自己的个人登录名来访问校园网站的这一部分。这将使这些凭据成为私有。
希望这有帮助!
Often times I've realized that remembering the basic concepts of any language can made possible by creating real-world analogies. Here is my analogy for understanding access modifiers in Java:
Let's assume that you're a student at a university and you have a friend who's coming to visit you over the weekend. Suppose there exists a big statue of the university's founder in the middle of the campus.
When you bring him to the campus, the first thing that you and your friend sees is this statue. This means that anyone who walks in the campus can look at the statue without the university's permission. This makes the statue as PUBLIC.
Next, you want to take your friend to your dorm, but for that you need to register him as a visitor. This means that he gets an access pass (which is the same as yours) to get into various buildings on campus. This would make his access card as PROTECTED.
Your friend wants to login to the campus WiFi but doesn't have the any credentials to do so. The only way he can get online is if you share your login with him. (Remember, every student who goes to the university also possesses these login credentials). This would make your login credentials as NO MODIFIER.
Finally, your friend wants to read your progress report for the semester which is posted on the website. However, every student has their own personal login to access this section of the campus website. This would make these credentials as PRIVATE.
Hope this helps!
当您考虑访问修饰符时,只需以这种方式考虑它(适用于变量和方法):
public
- &gt;可以从每个地方访问私有
- &gt;仅在现在声明的同一类中访问,当涉及
默认>
和preected
默认
default - &gt;没有访问修饰符关键字。这意味着它可以严格在类的包装中使用。 无处外部可以访问该包装。
受保护
- &gt;比默认
少一些,除了相同的软件包类外,它可以通过 package 之外的子类访问。When you are thinking of access modifiers just think of it in this way (applies to both variables and methods):
public
--> accessible from every whereprivate
--> accessible only within the same class where it is declaredNow the confusion arises when it comes to
default
andprotected
default
--> No access modifier keyword is present. This means it is available strictly within the package of the class. Nowhere outside that package it can be accessed.protected
--> Slightly less stricter thandefault
and apart from the same package classes it can be accessed by sub classes outside the package it is declared.这一切都是关于封装(或正如乔·菲利普斯(Joe Phillips)所述,最少知识)。
从最限制的(私有)开始,看看以后是否需要限制性修饰符较少。
我们都使用私人,公共的方法和成员修饰符,...但是,很少有开发人员使用软件包来逻辑地组织代码。
例如:
您可以将敏感的安全方法放在“安全”软件包中。
然后放置一个公共类,该课程访问此软件包中的一些与安全相关的代码,但请保留其他安全类 package private 。
因此,其他开发人员只能使用此软件包之外的公开可用类(除非他们更改修饰符)。
这不是安全功能,而是指南用法。
另一件事是,彼此之间很大程度上取决于彼此的类可能最终会属于同一软件包,并且如果依赖性太强,最终可能会重构或合并。
相反,如果您将所有内容设置为 public ,则不清楚应该访问或不应该访问什么,这可能会导致写很多Javadoc(不会通过编译器强制执行任何内容... )。
It is all about encapsulation (or as Joe Phillips stated, least knowledge).
Start with the most restrictive (private) and see if you need less restrictive modifiers later on.
We all use method and member modifiers like private, public, ... but one thing too few developers do is use packages to organize code logically.
For example:
You may put sensitive security methods in a 'security' package.
Then put a public class which accesses some of the security related code in this package but keep other security classes package private.
Thus other developers will only be able to use the publicly available class from outside of this package (unless they change the modifier).
This is not a security feature, but will guide usage.
Another thing is that classes which depend a lot on each other may end up in the same package and could eventually be refactored or merged if the dependency is too strong.
If on the contrary you set everything as public it will not be clear what should or should not be accessed, which may lead to writing a lot of javadoc (which does not enforce anything via the compiler...).
我的两分钱:)
私有:
class - &gt; 顶级类不能私有。内部类可以是私人,可以从同一类访问。
实例变量 - &gt; 仅在类中访问。无法在班级外访问。
软件包 - 私有化:
class-&gt; 顶级类可以是包装私有化的。它只能从同一软件包中访问。不是从子软件包中,而不是外部包装。
实例变量 - &gt; 可以从同一软件包访问。不是从子软件包中,而不是外部包装。
受保护:
类 - &gt; 无法保护顶级类。
实例变量 - &gt; 仅在同一软件包或子包中访问。在扩展课程时只能在包装外访问。
public:
class-&gt; 可从package/subpackage/又有另一个软件包
实例变量 - &gt; 可从package/subpackage/另一个软件包
访问详细的答案
https:/github.com/ junto06/java-4-beginners/blob/master/basics/access-modifier.md
My two cents :)
private:
class -> a top level class cannot be private. inner classes can be private which are accessible from same class.
instance variable -> accessible only in the class. Cannot access outside the class.
package-private:
class -> a top level class can be package-private. It can only be accessible from same package. Not from sub package, not from outside package.
instance variable -> accessible from same package. Not from sub package, not from outside package.
protected:
class -> a top level class cannot be protected.
instance variable -> Only accessible in same package or subpackage. Can only be access outside the package while extending class.
public:
class -> accessible from package/subpackage/another package
instance variable -> accessible from package/subpackage/another package
Here is detailed answer
https://github.com/junto06/java-4-beginners/blob/master/basics/access-modifier.md
软件包。适用于您要普遍公开的课程和方法。
继承:
类:
方法和字段:
子类别不能比其超级类别的超级级别的限制性访问权限。
packages. Suitable for classes and methods you want to expose universally.
Inheritance:
Classes:
Methods and Fields:
Subclasses can't have more restrictive access than their superclasses for overridden methods or fields.
对于初学者来说,考虑到这个示例可能会有所帮助;
考虑一下我在
foo
软件包中开发了myClass
,它具有一个名为print
您有兴趣调用的奇妙方法(这可能是一个方法
或属性
):您已经在
bar
软件包中开发了yourClass
,您有兴趣使用myClass#print
您的代码没有编译,并且您会获得错误
the Method print()对于
您来找我的类型myClass 您:您:
私有
。您可以将其公共
吗?其他
使用它不是其他
使用它。私有
关键字。我的访问修饰符将为默认
或私有软件包
。当您是我的朋友时,您必须与我处于同一包裹。因此,您必须
来到我的软件包foo
。我的意思是确切的软件包甚至都不是子软件包。然后
myClass
将是YourClass
将是:现在考虑一下:您再次来找我
扩展
ME,并且我进行print()
preected
,然后无论您是否更改包装,都可以使用它。 (因此,子类始终会让您访问我的方法)。这是
myClass
这是
YourClass
:您可能已经注意到,通过制作一种方法,可以通过所有其他类都可以通过
扩展< /code> it,您无法轻易控制如何使用它。在允许
单词。因此,您可以定义哪个
类可以
扩展您。通过公共密封类myClass允许您的级别
参见 Java 17中的密封类是什么? em>有关更多信息。
For beginners, considering this example can be helpful;
Consider I have developed
MyClass
in thefoo
package and it has a fantastic method namedprint
which you are interested in calling it (it could be amethod
orproperty
):You have developed
YourClass
inbar
package, and you are interested to useMyClass#print
Your code is not compile and you get error
The method print() is undefined for the type MyClass
You come to me:
private
. Can you make itpublic
?others
use itnot others
use it.private
keyword. My Access modifier will bedefault
orprivate package
. As you are my friend you must be in same package as me. So youmust
come to my packagefoo
. I mean exact package not even a sub package.Then
MyClass
will beYourClass
will be:Now consider this: Again you come to me
extend
me and I makeprint()
protected
, then you can use it whether you change you package or not. (So subclassing will always give you access to my method).Here is
MyClass
Here is
YourClass
:You may have noticed that by making a method protected all other classes can use it by
extending
it, and you can not easily control how it can be used. This was solved in Java 17 by introducingsealed
andpermits
words. So you can definewhich
classescan
extend you. By something likepublic sealed class MyClass permits YourClass
See What are sealed classes in Java 17? for more information.
它是班级对象变量或方法简单提出的范围。
如果您希望其他软件包/文件夹可以访问类变量,请使用 public !
使用受保护的如果可以的话,您不希望其他访问班级变量的软件包/文件夹。
如果您不希望其他访问班级变量的软件包/文件夹,则使用 no Modifer ,并且您不希望班级的子类访问它们,但是您仍然希望它们在软件包中访问。 (也称为“软件包 - 私有化”)
使用私有,如果您不希望其他访问班级变量的软件包/文件夹,并且您不希望班级的子类访问它们,并且您不希望您希望它们在包装中的其他任何地方都可以访问。
It is the scope of a Class's Object variables or methods simply put.
Use Public if you want your Class variables to be accessible by even other packages/folders!
Use Protected if okay you don't want other packages/folders accessing your Class's variables.
Use No Modifer if you don't want other packages/folders accessing your Class's variables and you don't want your Class's subclasses to access them, but you still want them accessible in the package. (Also called "Package-Private")
Use Private if you don't want other packages/folders accessing your Class's variables and you don't want your Class's subclasses to access them, and you don't want them accessible anywhere else in the package.
如果宣布班级成员是公开的,则可以从任何地方访问
如果按关键字保护了类成员,则可以从同一类成员,同一软件包内的外部成员以及继承的类成员访问。如果保护类成员,则无法从外部软件包类访问,除非继承外部包装类,即扩展其他软件包超级类。但是,受保护的类成员始终可用于同一软件包类,无论同一软件包类是继承的
是否都没有关系。
默认
在Java中,默认值不是访问修饰符关键字。如果在没有任何访问修改器关键字的情况下声明了类成员,则将其视为默认成员。默认类成员始终可用于同一软件包类成员。但是外部包装类成员也无法访问默认类成员,即使外部类是子类别,也不同于受保护成员
private
如果按关键字保护了类成员,则在这种情况下仅适用于同一类成员
If a class member is declared to be public then it can be accessed from anywhere
protected
If a class member is declared with keyword protected, it can be accessed from the same class members, outside class members within the same package, and inherited class members. If a class member is protected then it can NOT be accessed from an outside package class unless the outside packaged class is inherited i.e. extends the other package superclass. But a protected class member is always available to the same package classes it does NOT matter whether the same package class is inherited or NOT
default
In Java default is NOT an access modifier keyword. If a class member is declared without any access modifier keyword, it is considered a default member. The default class member is always available to the same package class members. But outside package class members can NOT access default class members even if outside classes are subclasses unlike protected members
private
If a class member is declared with keyword protected then in this case it is available ONLY to the same class members