Java中的公众,受保护,包裹私有和私人有什么区别?

发布于 2025-01-23 19:57:12 字数 179 浏览 6 评论 0 原文

在Java中,是否有明确的规则,即何时使用访问修饰符,即默认值(package private), public 受保护 and private private ,在制作 class 接口并处理继承时?

In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

眼波传意 2025-01-30 19:57:12

官方教程可能对您有所使用。


软件包子 同一pkg) (diff pkg world
✔️✔️✔️✔️✔️✔️✔️ public fublic
) <


❌:无法访问

The official tutorial may be of some use to you.


Class Package Subclass
(same pkg)
Subclass
(diff pkg)
World
public ✔️ ✔️ ✔️ ✔️ ✔️
protected ✔️ ✔️ ✔️ ✔️
no modifier ✔️ ✔️ ✔️
private ✔️

✔️: accessible
❌: not accessible

你怎么这么可爱啊 2025-01-30 19:57:12

(警告:我不是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.

物价感观 2025-01-30 19:57:12

这是表格的更好版本,还包括一个用于模块的列。

在此处输入图像描述“


说明

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

enter image description here


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:

  • A field long internalCounter should probably be private since it's mutable and an implementation detail.
  • A class that should only be instantiated in a factory class (in the same package) should have a package restricted constructor, since it shouldn't be possible to call it directly from outside the package.
  • An internal void beforeRender() method called right before rendering and used as a hook in subclasses should be protected.
  • A void saveGame(File dst) method which is called from the GUI code should be public.

(*) What is Encapsulation exactly?

机场等船 2025-01-30 19:57:12
____________________________________________________________________
                | highest precedence <---------> lowest precedence
*———————————————+———————————————+———————————+———————————————+———————
 \ xCanBeSeenBy | this          | any class | this subclass | any
  \__________   | class         | in same   | in another    | class
             \  | nonsubbed     | package   | package       |
Modifier of x \ |               |           |               |
————————————————*———————————————+———————————+———————————————+———————
public          |       ✔       |     ✔     |       ✔       |   ✔
————————————————+———————————————+———————————+———————————————+———————
protected       |       ✔       |     ✔     |       ✔       |   ✘
————————————————+———————————————+———————————+———————————————+———————
package-private |               |           |               |
(no modifier)   |       ✔       |     ✔     |       ✘       |   ✘
————————————————+———————————————+———————————+———————————————+———————
private         |       ✔       |     ✘     |       ✘       |   ✘
____________________________________________________________________
____________________________________________________________________
                | highest precedence <---------> lowest precedence
*———————————————+———————————————+———————————+———————————————+———————
 \ xCanBeSeenBy | this          | any class | this subclass | any
  \__________   | class         | in same   | in another    | class
             \  | nonsubbed     | package   | package       |
Modifier of x \ |               |           |               |
————————————————*———————————————+———————————+———————————————+———————
public          |       ✔       |     ✔     |       ✔       |   ✔
————————————————+———————————————+———————————+———————————————+———————
protected       |       ✔       |     ✔     |       ✔       |   ✘
————————————————+———————————————+———————————+———————————————+———————
package-private |               |           |               |
(no modifier)   |       ✔       |     ✔     |       ✘       |   ✘
————————————————+———————————————+———————————+———————————————+———————
private         |       ✔       |     ✘     |       ✘       |   ✘
____________________________________________________________________
吃兔兔 2025-01-30 19:57:12

简单的规则。首先宣布一切私人。然后随着需求的出现和设计而朝着公众迈进。

暴露成员时,问自己是否正在公开表示的选择或抽象选择。首先是您要避免的事情,因为它会引入太多对实际表示形式而不是可观察到的行为的依赖性。

作为一般规则,我试图避免通过子分类来避免覆盖方法实现;搞砸逻辑太容易了。如果您打算覆盖抽象的方法,请声明抽象保护方法。

另外,在覆盖时,请使用@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.

ζ澈沫 2025-01-30 19:57:12

实际上,它比简单的网格显示要复杂一些。网格告诉您是否允许访问,但是究竟是什么构成访问权限?此外,访问级别以复杂的方式与嵌套类和继承相互作用。

“默认”访问(由缺少关键字指定)也称为 package-package-package-private < /strong> 。例外:在接口中,没有修改器意味着公共访问;禁止公众以外的其他修饰符。枚举常数始终是公开的。

摘要

是否允许使用此访问说明符对成员的访问?

  • 成员是私有:仅当成员与调用代码同一类中定义。
  • 成员是私人包装:只有当调用代码在会员的立即包装软件包中时,才有成员。
  • 成员IS 受保护:相同的软件包,或者如果在包含调用代码的类的超级类别中定义了成员。
  • 成员是 public :是。

访问说明符适用于

本地变量和正式参数无法访问访问说明符。由于根据范围的规则,它们本质上无法访问外部,因此实际上是私人的。

对于顶部范围中的课程,仅允许 public 和软件包私有化。这种设计选择大概是因为受保护的私有在软件包级别上是多余的(没有包装的继承)。

类成员(构造函数,方法和静态成员函数,嵌套类)上所有访问说明符都是可能的。

相关: Java类可访问性

订购访问

访问说明器可以严格订购

public&gt;受保护&gt;包装私有化&gt;私人

含义 public 提供了最多的访问权限,私有至少。私人成员可能的任何参考也适用于软件包私人会员;对软件包私有化成员的任何引用对受保护的成员有效,依此类推。 中访问受保护的会员是错误的

  • (在同一软件包 em>是允许访问同一类其他对象的私人成员。更确切地说,C类C可以在C. Java的任何子类的对象上访问C级私人成员支持按实例限制访问权限,仅划分。 (与Scala进行比较,Scala确实使用 private [this] 。)
  • 您需要访问构造函数来构造对象。因此,如果所有构造函数都是私有的,则只能通过生活在类中的代码来构造(通常是静态出厂方法或静态变量初始化器)。类似地用于包装私有或受保护的构造函数。
    • 只有私人构造函数也意味着不能在外部进行群体分类,因为Java要求子类的构造函数隐式或显式地调用超级类构造函数。 (但是,它可以包含一个将其分类的嵌套类。)

您还必须考虑 nested 示波器,例如内部类 复杂性的一个例子是内部类有成员,他们自己可以使用访问修饰符。因此,您可以与公共成员一起拥有一个私人内部班级;可以访问成员吗? (请参见下文。)一般规则是查看范围并递归思考,以查看是否可以访问每个级别。

但是,这很复杂,并且有关全部详细信息,咨询Java语言规范。 (是的,过去有编译器的错误。)

为了考虑这些相互作用的方式,请考虑此示例。可以“泄漏”私人内部类;这通常是一个警告:

class Test {
    public static void main(final String ... args) {
        System.out.println(Example.leakPrivateClass()); // OK
        Example.leakPrivateClass().secretMethod(); // error
    }
}

class Example {
    private static class NestedClass {
        public void secretMethod() {
            System.out.println("Hello");
        }
    }
    public static NestedClass leakPrivateClass() {
        return new NestedClass();
    }
}

编译器输出:

Test.java:4: secretMethod() in Example.NestedClass is defined in an inaccessible class or interface
        Example.leakPrivateClass().secretMethod(); // error
                                  ^
1 error

一些相关问题:

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?

  • Member is private: Only if member is defined within the same class as calling code.
  • Member is package private: Only if the calling code is within the member's immediately enclosing package.
  • Member is protected: Same package, or if member is defined in a superclass of the class containing the calling code.
  • Member is 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 because protected and private 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

public > protected > package-private > private

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

  • A class's methods are allowed to access private members of other objects of the same class. More precisely, a method of class C can access private members of C on objects of any subclass of C. Java doesn't support restricting access by instance, only by class. (Compare with Scala, which does support it using private[this].)
  • You need access to a constructor to construct an object. Thus if all constructors are private, the class can only be constructed by code living within the class (typically static factory methods or static variable initializers). Similarly for package-private or protected constructors.
    • Only having private constructors also means that the class cannot be subclassed externally, since Java requires a subclass's constructors to implicitly or explicitly call a superclass constructor. (It can, however, contain a nested class that subclasses it.)

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:

class Test {
    public static void main(final String ... args) {
        System.out.println(Example.leakPrivateClass()); // OK
        Example.leakPrivateClass().secretMethod(); // error
    }
}

class Example {
    private static class NestedClass {
        public void secretMethod() {
            System.out.println("Hello");
        }
    }
    public static NestedClass leakPrivateClass() {
        return new NestedClass();
    }
}

Compiler output:

Test.java:4: secretMethod() in Example.NestedClass is defined in an inaccessible class or interface
        Example.leakPrivateClass().secretMethod(); // error
                                  ^
1 error

Some related questions:

走走停停 2025-01-30 19:57:12

根据经验法则:

  • 私有:类范围。
  • 默认值(或 package-Provate ):软件包范围。
  • 保护软件包范围 +儿童(如软件包,但我们可以从不同的软件包子中进行子类)。受保护的修饰符始终保持“亲子”关系。
  • public :无处不在。

结果,如果我们将访问权利划分为三个权利:

  • (d)Airct (从同一类内的方法调用或通过“此”语法)。
  • (r)ceference (使用对类的引用或通过“ dot”语法调用方法)。
  • (i)nheritance (通过子类)。

然后我们有一个简单的表:

+—-———————————————+————————————+———————————+
|                 |    Same    | Different |
|                 |   Package  | Packages  |
+—————————————————+————————————+———————————+
| private         |   D        |           |
+—————————————————+————————————+———————————+
| package-private |            |           |
| (no modifier)   |   D R I    |           |
+—————————————————+————————————+———————————+
| protected       |   D R I    |       I   |
+—————————————————+————————————+———————————+
| public          |   D R I    |    R  I   |
+—————————————————+————————————+———————————+

As a rule of thumb:

  • private: class scope.
  • default (or package-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:

  • (D)irect (invoke from a method inside the same class, or via "this" syntax).
  • (R)eference (invoke a method using a reference to the class, or via "dot" syntax).
  • (I)nheritance (via subclassing).

then we have this simple table:

+—-———————————————+————————————+———————————+
|                 |    Same    | Different |
|                 |   Package  | Packages  |
+—————————————————+————————————+———————————+
| private         |   D        |           |
+—————————————————+————————————+———————————+
| package-private |            |           |
| (no modifier)   |   D R I    |           |
+—————————————————+————————————+———————————+
| protected       |   D R I    |       I   |
+—————————————————+————————————+———————————+
| public          |   D R I    |    R  I   |
+—————————————————+————————————+———————————+
時窥 2025-01-30 19:57:12

在非常简短的

  • 公共中:可从任何地方访问。
  • 受保护:可通过同一软件包的类和任何软件包中的子类访问。
  • 默认值(未指定修改器):可以通过同一软件包的类访问。
  • 私有:仅在同一类中访问。

In very short

  • public: accessible from everywhere.
  • protected: accessible by the classes of the same package and the subclasses residing in any package.
  • default (no modifier specified): accessible by the classes of the same package.
  • private: accessible within the same class only.
白色秋天 2025-01-30 19:57:12

Java中最误解的访问修饰符是受保护。我们知道它类似于默认修饰符,一个例外,子类可以看到它。但是如何?这是一个示例,希望能阐明混乱:

  • 假设我们有2个课程; 父亲 son ,每个>在其自己的软件包中:

      package autypackage;
    
    公共班父亲
    {
    
    }
    
    ------------------------------------------------------------
    
    包裹sonpackage;
    
    公共班儿子延长父亲
    {
    
    }
     
  • 让我们添加一个受保护的方法 foo() >。

      package autypackage;
    
    公共班父亲
    {
        受保护的void foo(){}
    }
     
  • 方法 foo()可以在4个上下文中调用:

    1. 在同一软件包中的一类内部定义 foo()

        package autypackage;
      
      公共类躯体
      {
          公共无效的物种(父亲F,儿子S)
          {
              f.foo();
              s.foo();
          }
      }
       

    2. 在一个子类内,在当前实例上通过 super

       软件包sonpackage;
      
      公共班儿子延长父亲
      {
          公共无效SonMethod()
          {
              this.foo();
              super.foo();
          }
      }
       
    3. 在引用的类型是同一类的引用上:

        package autypackage;
      
      公共班父亲
      {
          公共空白Fathermethod(父亲F)
          {
              f.foo(); //有效,即使foo()是私有的
          }
      }
      
      ------------------------------------------------------------
      
      包裹sonpackage;
      
      公共班儿子延长父亲
      {
          公共无效SonMethod(儿子)
          {
              s.foo();
          }
      }
       
    4. 在引用其类型是父类的引用上,它是 foo()定义的软件包( auth> autherpackage )[这可以包含在上下文中。 1]:

        package autypackage;
      
      公共班儿子延长父亲
      {
          公共空白Sonmethod(父亲F)
          {
              f.foo();
          }
      }
       
  • 以下情况无效。

    1. 在引用其类型为父类的引用上,它是 exter foo()定义的软件包( auth> autherpackage ):

       软件包sonpackage;
      
      公共班儿子延长父亲
      {
          公共空白Sonmethod(父亲F)
          {
              f.foo(); //编译错误
          }
      }
       
    2. 一个子类包装中的非群典(子类从其父母那里继承了受保护的成员,它使其成为非群体的私人):

       软件包sonpackage;
      
      公共类躯体
      {
          公共无效的物种(儿子)抛出例外
          {
              s.foo(); //编译错误
          }
      }
       

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 and Son, each in its own package:

    package fatherpackage;
    
    public class Father
    {
    
    }
    
    -------------------------------------------
    
    package sonpackage;
    
    public class Son extends Father
    {
    
    }
    
  • Let's add a protected method foo() to Father.

    package fatherpackage;
    
    public class Father
    {
        protected void foo(){}
    }
    
  • The method foo() can be called in 4 contexts:

    1. Inside a class that is located in the same package where foo() is defined (fatherpackage):

      package fatherpackage;
      
      public class SomeClass
      {
          public void someMethod(Father f, Son s)
          {
              f.foo();
              s.foo();
          }
      }
      
    2. Inside a subclass, on the current instance via this or super:

      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod()
          {
              this.foo();
              super.foo();
          }
      }
      
    3. On an reference whose type is the same class:

      package fatherpackage;
      
      public class Father
      {
          public void fatherMethod(Father f)
          {
              f.foo(); // valid even if foo() is private
          }
      }
      
      -------------------------------------------
      
      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Son s)
          {
              s.foo();
          }
      }
      
    4. 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]:

      package fatherpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Father f)
          {
              f.foo();
          }
      }
      
  • The following situations are not valid.

    1. On an reference whose type is the parent class and it is outside the package where foo() is defined (fatherpackage):

      package sonpackage;
      
      public class Son extends Father
      {
          public void sonMethod(Father f)
          {
              f.foo(); // compilation error
          }
      }
      
    2. 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):

      package sonpackage;
      
      public class SomeClass
      {
          public void someMethod(Son s) throws Exception
          {
              s.foo(); // compilation error
          }
      }
      
拥抱没勇气 2025-01-30 19:57:12

private

  • 方法,变量和构造函数

方法,变量和构造函数只能在声明的类本身中访问私有。

  • 类和接口

private访问修改器大多数限制性访问级别。类和界面不能私有。

注释

,如果班级中存在公共getter方法,则可以在类外访问私有的变量。
在超类中声明的变量,方法和构造函数只能由其他软件包中的子类或受保护成员类的软件包中的任何类访问。


受保护的

  • 类和界面

不能将受保护的访问修饰符应用于类和接口。

方法,可以声明字段受到保护,但是方法但是方法界面中的字段不能被

声明

。尝试使用它的非相关类。


public

可以从任何其他类访问公共的类,方法,构造函数,界面等。

因此,在公共类中声明的字段,方法,块可以是从属于Java Universe的任何类访问。

  • 不同的软件包

但是,如果我们要访问的公共类是在其他软件包中导入。

由于类继承,所有类的公共方法和变量均由其子类继承。


默认-no关键字:

默认访问修改器表示我们没有明确声明同一

  • 软件包内的类,字段,方法等的访问修饰符

在同一软件包中的任何其他类都可以使用任何访问控制修饰符的变量或方法。界面中的字段是隐式的公共静态最终最终的,默认接口中的方法是公开的。

note

我们不能覆盖静态字段。如果您尝试尝试要覆盖它不会显示任何错误
但这不起作用,除了我们之外。

相关答案

  • Java

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

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

  • Class and Interface

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

  • Class and Interface

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.

  • Different Packages

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.

  • Within the same Packages

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

硪扪都還晓 2025-01-30 19:57:12

java访问修饰符

”在此处输入图像说明“

访问修饰符可用于 class , field [of] 方法。尝试访问,子类或覆盖此问题。

  • 访问字段方法是通过 class
  • 继承和打开关闭原理 [关于]
    • 连续 class (子类)访问修饰符可以是任何
    • 连续方法(覆盖)访问修饰符应为相同或展开

顶级类(第一级范围)可以是 public 默认 [关于]

嵌套类 >软件包不申请软件包层次结构

[swift访问访问修饰符]

Java access modifiers

enter image description here

Access modifier can be applicable for class, field[About], method. Try to access, subclass or override this.

  • Access to field or method is through a class.
  • Inheritance and Open Closed Principle[About]
    • Successor class(subclass) access modifier can be any.
    • Successor method(override) access modifier should be the same or expand it

Top level class(first level scope) can be public and default. Nested class[About] can have any of them

package is not applying for package hierarchy

[Swift access modifiers]

不疑不惑不回忆 2025-01-30 19:57:12

差异可以在已经提供的链接中找到,但是使用哪个链接通常取决于“最少知识的原则”。仅允许所需的知名度最低。

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.

悲欢浪云 2025-01-30 19:57:12

私人:仅访问类

默认值(无修饰符):有限的访问类别和软件包

受保护:有限的访问类,软件包和子类(内部和外部包)

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.

潦草背影 2025-01-30 19:57:12

访问修饰符有多个级别限制访问。

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.

荒路情人 2025-01-30 19:57:12

Java中的访问修饰符。

Java访问修饰符用于在Java中提供访问控制。

1。默认值:

仅在同一软件包中的类可访问。

例如,

// Saved in file A.java
package pack;

class A{
  void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A(); // Compile Time Error
   obj.msg(); // Compile Time Error
  }
}

此访问比公共和受保护更受限制,但比私人限制更少。

2。公共

可以从任何地方访问。 (全局访问)

例如,

// Saved in file A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

// Saved in file B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
    A obj = new A();
    obj.msg();
  }
}

输出:你好

3。私人

仅在同一类内访问。

如果您尝试访问另一个类中的私人会员,则会丢弃编译错误。例如,

class A{
  private int data = 40;
  private void msg(){System.out.println("Hello java");}
}

public class Simple{
  public static void main(String args[]){
    A obj = new A();
    System.out.println(obj.data); // Compile Time Error
    obj.msg(); // Compile Time Error
  }
}

4。受保护

仅在同一软件包中的类中访问

,例如

// Saved in file A.java
package pack;
public class A{
  protected void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B extends A{
  public static void main(String args[]){
    B obj = new B();
    obj.msg();
  }
}

输出:你好

在此处输入图像描述“

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,

// Saved in file A.java
package pack;

class A{
  void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A(); // Compile Time Error
   obj.msg(); // Compile Time Error
  }
}

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,

// Saved in file A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

// Saved in file B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
    A obj = new A();
    obj.msg();
  }
}

Output:Hello

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,

class A{
  private int data = 40;
  private void msg(){System.out.println("Hello java");}
}

public class Simple{
  public static void main(String args[]){
    A obj = new A();
    System.out.println(obj.data); // Compile Time Error
    obj.msg(); // Compile Time Error
  }
}

4. Protected

Accessible only to the classes in the same package and to the subclasses

For example,

// Saved in file A.java
package pack;
public class A{
  protected void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B extends A{
  public static void main(String args[]){
    B obj = new B();
    obj.msg();
  }
}

Output: Hello

Enter image description here

谁许谁一生繁华 2025-01-30 19:57:12

包裹可见。默认值。不需要修饰符。

仅对班级可见(私有)。

可见世界( public )。

包装和所有子类可见(受保护)。

可以声明变量和方法,而无需任何调用符。默认示例:

String name = "john";

public int age(){
    return age;
}

私人访问修饰符 - 私有:

声明为私有的方法,变量和构造函数只能在声明的类本身中访问。私人访问修饰符是最严格的访问级别。类和界面不能私有。

如果班级中存在公共Getter方法,则可以在班级外访问私有的变量。

使用私有修饰符是对象封装自身并隐藏外界数据的主要方式。

示例:

Public class Details{

    private String name;

    public void setName(String n){
        this.name = n;
    }

    public String getName(){
        return this.name;
    }
}

公共访问修饰符 - 公共:

类,方法,构造函数,接口等。可以从任何其他类访问公共声明。因此,可以从属于Java宇宙的任何类中访问公共类中声明的字段,方法,块。

但是,如果我们试图访问的公共类是在另一个软件包中,则仍然需要进口公共类。

由于阶级继承,类的所有公共方法和变量均由其子类继承。

示例:

public void cal(){

}

受保护的访问修饰符 - 受保护:

在超类中声明的变量,方法和构造函数只能由另一个软件包中的子类别或受保护成员类的软件包中的任何类中的子类访问。

受保护的访问修饰符不能应用于类和界面。方法,字段可以被声明保护,但是接口中的方法和字段不能被声明受保护。

受保护的访问使子类有机会使用助手方法或变量,同时防止非相关类尝试使用它。

class Van{

    protected boolean speed(){

    }
}

class Car{
    boolean speed(){
    }

}

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:

String name = "john";

public int age(){
    return age;
}

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 class Details{

    private String name;

    public void setName(String n){
        this.name = n;
    }

    public String getName(){
        return this.name;
    }
}

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:

public void cal(){

}

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.

class Van{

    protected boolean speed(){

    }
}

class Car{
    boolean speed(){
    }

}
淤浪 2025-01-30 19:57:12
  • 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.

倾听心声的旋律 2025-01-30 19:57:12

此页面关于受保护的&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.
....

柏林苍穹下 2025-01-30 19:57:12

大卫的答案提供了每个访问修饰符的含义。至于何时使用,我建议公开所有班级和旨在外部用途(其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.

爱她像谁 2025-01-30 19:57:12

此图像将使您轻松了解公共,私人,受保护和默认访问修饰符之间的基本差异。当您不声明代码中的蚂蚁访问修饰符时,默认修饰符会自动进行。

Differences between public, private, default and protected access modifiers

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.

清泪尽 2025-01-30 19:57:12

公共受保护的默认值和私人是访问修饰符。

它们是用于封装或隐藏和显示班级内容的内容。

  1. 类可以是公共或默认
  2. 类成员可以是公共,受保护,默认或私人的。

私人在班上不可访问
默认值仅在软件包中访问。
在包装中受保护以及任何扩展它的类。
公众对所有人开放。

通常,会员变量是私人定义的,但成员方法是公开的。

Public Protected Default and private are access modifiers.

They are meant for encapsulation, or hiding and showing contents of the class.

  1. Class can be public or default
  2. Class members can be public, protected, default or private.

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.

日久见人心 2025-01-30 19:57:12

注意:这只是接受答案的补充

这与Java 访问修饰符

来自 java访问修饰符

Java访问修饰符指定哪些类可以访问给定的
类及其字段,构造函数和方法。访问修饰符可以
分别为班级,其构造函数,字段和
方法。 Java访问修饰符有时也会在每天参考
语音为Java访问说明符,但正确的名称是Java访问
修饰符。类,字段,构造函数和方法可以拥有
四个不同的Java访问修饰符:

  • 列表项目
  • 私人
  • 默认(软件包)
  • 受保护
  • 公共

来自教程:

访问级别修饰符确定其他类是否可以使用
特定字段或调用特定方法。有两个级别
访问控制:

  • 在最高级别 - 公共或软件包 - 私有化(无明确的修饰符)。
  • 在成员级别 - 公共,私人,受保护或包装私有化(无明确的修饰符)。

可以向修饰符公众声明一个类,在这种情况下
各地的所有课程都可以看到课程。如果课程没有修饰符
(默认值,也称为包裹私有化),仅可见
在自己的软件包中

下表显示了对每个成员允许的访问
修饰符。

 ╔═════════════╦═══════╦═════════╦══════════╦ ═══════╗
║修饰符║类║包装║子类别║世界║世界║
╠═════════════╬═══════╬═════════╬══════════╬══════ ═╣
║public║y║y║y║
║受保护的║y║y y║n║
║无修饰符║y y║y║n║n║
║私有║
╚═════════════╩═══════╩═════════╩══════════╩══════ ═╝
 

第一个数据列指示类本身是否可以访问
由访问级别定义的成员。如您所见,一堂课总是
可以访问自己的成员。第二列指示是否
与班级同一包中的课程(无论他们如何
parentage)可以访问会员。第三列指示
该包外的班级子类是否有
访问会员。第四列指示是否所有类
可以访问会员。

访问级别以两种方式影响您。首先,当您使用类
来自另一个来源,例如Java平台中的类,
访问级别确定您自己的这些课程的哪些成员
课程可以使用。第二,当您写课时,您需要决定
每个成员变量的访问级别以及类中的每个方法
应该有。

Note: This is just a supplement for the accepted answer.

This is related to Java Access Modifiers.

From Java Access Modifiers:

A Java access modifier specifies which classes can access a given
class and its fields, constructors and methods. Access modifiers can
be specified separately for a class, its constructors, fields and
methods. Java access modifiers are also sometimes referred to in daily
speech as Java access specifiers, but the correct name is Java access
modifiers. Classes, fields, constructors and methods can have one of
four different Java access modifiers:

  • List item
  • private
  • default (package)
  • protected
  • public

From Controlling Access to Members of a Class tutorials:

Access level modifiers determine whether other classes can use a
particular field or invoke a particular method. There are two levels
of access control:

  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—public, private, protected, or package-private (no explicit modifier).

A class may be declared with the modifier public, in which case that
class is visible to all classes everywhere. If a class has no modifier
(the default, also known as package-private), it is visible only
within its own package

The following table shows the access to members permitted by each
modifier.

╔═════════════╦═══════╦═════════╦══════════╦═══════╗
║ Modifier    ║ Class ║ Package ║ Subclass ║ World ║
╠═════════════╬═══════╬═════════╬══════════╬═══════╣
║ public      ║ Y     ║ Y       ║ Y        ║ Y     ║
║ protected   ║ Y     ║ Y       ║ Y        ║ N     ║
║ no modifier ║ Y     ║ Y       ║ N        ║ N     ║
║ private     ║ Y     ║ N       ║ N        ║ N     ║
╚═════════════╩═══════╩═════════╩══════════╩═══════╝

The first data column indicates whether the class itself has access to
the member defined by the access level. As you can see, a class always
has access to its own members. The second column indicates whether
classes in the same package as the class (regardless of their
parentage) have access to the member. The third column indicates
whether subclasses of the class declared outside this package have
access to the member. The fourth column indicates whether all classes
have access to the member.

Access levels affect you in two ways. First, when you use classes that
come from another source, such as the classes in the Java platform,
access levels determine which members of those classes your own
classes can use. Second, when you write a class, you need to decide
what access level every member variable and every method in your class
should have.

黒涩兲箜 2025-01-30 19:57:12

通常,我意识到,记住任何语言的基本概念都可以通过创建现实世界的类比来实现。这是我的类比,用于了解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!

诠释孤独 2025-01-30 19:57:12

当您考虑访问修饰符时,只需以这种方式考虑它(适用于变量方法):

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 where
private --> accessible only within the same class where it is declared

Now the confusion arises when it comes to default and protected

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 than default and apart from the same package classes it can be accessed by sub classes outside the package it is declared.

驱逐舰岛风号 2025-01-30 19:57:12

这一切都是关于封装(或正如乔·菲利普斯(Joe Phillips)所述,最少知识)。

从最限制的(私有)开始,看看以后是否需要限制性修饰符较少。

我们都使用私人,公共的方法和成员修饰符,...但是,很少有开发人员使用软件包来逻辑地组织代码。

例如:
您可以将敏感的安全方法放在“安全”软件包中。
然后放置一个公共类,该课程访问此软件包中的一些与安全相关的代码,但请保留其他安全类 package private
因此,其他开发人员只能使用此软件包之外的公开可用类(除非他们更改修饰符)。
这不是安全功能,而是指南用法。

Outside world -> Package (SecurityEntryClass ---> Package private classes)

另一件事是,彼此之间很大程度上取决于彼此的类可能最终会属于同一软件包,并且如果依赖性太强,最终可能会重构或合并。

相反,如果您将所有内容设置为 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.

Outside world -> Package (SecurityEntryClass ---> Package private classes)

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

︶ ̄淡然 2025-01-30 19:57:12

我的两分钱:)

私有:

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

你曾走过我的故事 2025-01-30 19:57:12
  1. public:在您的代码库中使用广泛的可访问性
    软件包。适用于您要普遍公开的课程和方法。
  2. 受保护:在同一软件包和子类中,即使在不同的软件包中也提供访问。对于平衡封装与子类访问有用。
  3. 默认值(软件包私有):无明确的修饰符;在同一软件包中可访问。提供封装,同时允许在包装中访问。
  4. 私人:限制了班级的访问。隐藏其他类别实施详细信息的理想选择。

继承:

类:

  1. public:任何班级都可以取代。
  2. 受保护:在同一包装中和不同的包装中可亚分。
  3. 默认值:在同一软件包中可划分。
  4. 私人:不可用。

方法和字段:

  1. 公共:到处都是可访问的。
  2. 受保护:在同一软件包和子类中可访问。
  3. 默认值:在同一软件包中可访问。
  4. 私人:仅在同一类中访问。

子类别不能比其超级类别的超级级别的限制性访问权限。

  1. public: Use for wide accessibility across your codebase and in different
    packages. Suitable for classes and methods you want to expose universally.
  2. protected: Provides access within the same package and in subclasses, even in different packages. Useful for balancing encapsulation with subclass access.
  3. Default (Package Private): No explicit modifier; accessible within the same package. Offers encapsulation while allowing access within a package.
  4. private: Restricts access to within the class. Ideal for hiding implementation details from other classes.

Inheritance:

Classes:

  1. public: Subclassable by any class.
  2. protected: Subclassable within the same package and in different packages.
  3. Default: Subclassable within the same package.
  4. private: Not subclassable.

Methods and Fields:

  1. public: Accessible everywhere.
  2. protected: Accessible within the same package and in subclasses.
  3. Default: Accessible within the same package.
  4. private: Accessible only within the same class.

Subclasses can't have more restrictive access than their superclasses for overridden methods or fields.

罗罗贝儿 2025-01-30 19:57:12

对于初学者来说,考虑到这个示例可能会有所帮助;

考虑一下我在 foo 软件包中开发了 myClass ,它具有一个名为 print 您有兴趣调用的奇妙方法(这可能是一个方法属性):

package foo;  // I am in foo
public class MyClass {
     private void print() { //This is private
        System.out.println("I can print!");
    }
}

您已经在 bar 软件包中开发了 yourClass ,您有兴趣使用 myClass#print

package bar; \\You are not in same package as me
import foo.MyClass;
public class YourClass {
    void test() {
        MyClass myClass = new MyClass();
        myClass.print();
    }
}

您的代码没有编译,并且您会获得错误 the Method print()对于

您来找我的类型myClass 您:您:

  • 您:我:我想使用您的方法,但是它是私有。您可以将其公共吗?
  • 我:不,我不想要其他使用它
  • :我是你的朋友,至少让我不是其他使用它。
  • 我:好的,我将删除私有关键字。我的访问修饰符将为默认私有软件包。当您是我的朋友时,您必须与我处于同一包裹。因此,您必须来到我的软件包 foo 。我的意思是确切的软件包甚至都不是子软件包。

然后 myClass 将是

package foo;
public class MyClass {
    void print() { // No access modifier means default or package-private
        System.out.println("I can print!");
    }
}

YourClass 将是:

package foo;//You come to my package
public class YourClass {
    void test() {
        MyClass myClass = new MyClass();
        myClass.print();
    }
}

现在考虑一下:您再次来找我

  • :我的老板告诉我,我无法更改我的软件包(在现实世界中,您无法更改您的软件包以使用其他类方法)
  • 我:还有另一种方法,如果您扩展 ME,并且我进行 print() preected ,然后无论您是否更改包装,都可以使用它。 (因此,子类始终会让您访问我的方法)。

这是 myClass

package foo;
protected class MyClass { // It is now protected
     protected void print() {
        System.out.println("I can print!");
    }
}

这是 YourClass

package bar; // You are on your own package
import foo.MyClass;

public class YourClass extends MyClass {
    void  test() {
        // You initiate yourself! But as you extend me, you can call my print()
        YourClass yourClass = new YourClass();
        yourClass.print();
    }
}

您可能已经注意到,通过制作一种方法,可以通过所有其他类都可以通过扩展< /code> it,您无法轻易控制如何使用它。在允许单词。因此,您可以定义哪个可以扩展您。通过公共密封类myClass允许您的级别
参见
Java 17中的密封类是什么? em>有关更多信息。

For beginners, considering this example can be helpful;

Consider I have developed MyClass in the foo package and it has a fantastic method named print which you are interested in calling it (it could be a method or property):

package foo;  // I am in foo
public class MyClass {
     private void print() { //This is private
        System.out.println("I can print!");
    }
}

You have developed YourClass in bar package, and you are interested to use MyClass#print

package bar; \\You are not in same package as me
import foo.MyClass;
public class YourClass {
    void test() {
        MyClass myClass = new MyClass();
        myClass.print();
    }
}

Your code is not compile and you get error The method print() is undefined for the type MyClass

You come to me:

  • You: I want to use your method but it is private. Can you make it public?
  • Me : No I don't want others use it
  • You: I am your friend at least let me not others use it.
  • Me : Ok I will remove the private keyword. My Access modifier will be default or private package. As you are my friend you must be in same package as me. So you must come to my package foo. I mean exact package not even a sub package.

Then MyClass will be

package foo;
public class MyClass {
    void print() { // No access modifier means default or package-private
        System.out.println("I can print!");
    }
}

YourClass will be:

package foo;//You come to my package
public class YourClass {
    void test() {
        MyClass myClass = new MyClass();
        myClass.print();
    }
}

Now consider this: Again you come to me

  • You: My boss told me I can not change my package (in the actual world, you can not change your package to use other classes methods)
  • Me : There is another way, if you extend me and I make print() 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

package foo;
protected class MyClass { // It is now protected
     protected void print() {
        System.out.println("I can print!");
    }
}

Here is YourClass:

package bar; // You are on your own package
import foo.MyClass;

public class YourClass extends MyClass {
    void  test() {
        // You initiate yourself! But as you extend me, you can call my print()
        YourClass yourClass = new YourClass();
        yourClass.print();
    }
}

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 introducing sealed and permits words. So you can define which classes can extend you. By something like public sealed class MyClass permits YourClass
See What are sealed classes in Java 17? for more information.

撕心裂肺的伤痛 2025-01-30 19:57:12

它是班级对象变量或方法简单提出的范围。

如果您希望其他软件包/文件夹可以访问类变量,请使用 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.

![enter image description here

ぽ尐不点ル 2025-01-30 19:57:12

如果宣布班级成员是公开的,则可以从任何地方访问

  • 受保护

    如果按关键字保护了类成员,则可以从同一类成员,同一软件包内的外部成员以及继承的类成员访问。如果保护类成员,则无法从外部软件包类访问,除非继承外部包装类,即扩展其他软件包超级类。但是,受保护的类成员始终可用于同一软件包类,无论同一软件包类是继承的

    是否都没有关系。

  • 但是,受保护的类成员始终可用于同一软件包类,无论同一软件包类是继承

    默认

    在Java中,默认值不是访问修饰符关键字。如果在没有任何访问修改器关键字的情况下声明了类成员,则将其视为默认成员。默认类成员始终可用于同一软件包类成员。但是外部包装类成员也无法访问默认类成员,即使外部类是子类别,也不同于受保护成员

  • private

如果按关键字保护了类成员,则在这种情况下仅适用于同一类成员

  • public

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文