Java 类可访问性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/267781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:42:53  来源:igfitidea点击:

Java Class Accessibility

javaclassaccessibility

提问by Claudiu

Slightly related to my other question: What is the difference between the following:

与我的另一个问题略有相关:以下之间的区别是什么:

private class Joe
protected class Joe
public class Joe
class Joe

Once again, the difference between the last 2 is what I'm most interested in.

再一次,最后两个之间的区别是我最感兴趣的。

回答by erickson

A public class is accessible to a class in any package.

任何包中的类都可以访问公共类。

A class with default access (class Joe) is only visible to other classes in the same package.

具有默认访问权限 ( class Joe) 的类仅对同一包中的其他类可见。

The private and protected modifiers can only be applied to inner classes.

private 和 protected 修饰符只能应用于内部类。

A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.

私有类仅对其封闭类以及同一封闭类中的其他内部类可见。

A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.

受保护的类对同一包中的其他类以及扩展封闭类的类可见。

回答by Daniel Hiller

  • private: visible for outer classes only
  • protected: visible for outer classes only
  • public: visible for all other classes
  • class: package-private, so visible for classes within the same package
  • private:仅对外部类可见
  • 受保护:仅对外部类可见
  • public:对所有其他类可见
  • 类:包私有,对同一包中的类可见

See JLSfor more info.

有关更多信息,请参阅JLS

回答by VonC

A class with default accesshas no modifier preceding it in the declaration.

具有默认访问权限的类在声明中前面没有修饰符。

The default accessis a package-level access, because a class with default access can be seen only by classes within the same package.

默认的访问是一个包级别的访问,因为默认访问一个类只能在同一个包中的类可以看到。

If a class has default access, a class in another package won't be able to create a instance of that class, or even declare a variable or return type. The compiler will complain. For example:

如果类具有默认访问权限,则另一个包中的类将无法创建该类的实例,甚至无法声明变量或返回类型。编译器会抱怨。例如:

package humanity;
class Person {}

package family;
import humanity.Person;
class Child extends Person {}

Try to compile this 2 sources. As you can see, they are in different packages, and the compilation will fail.

尝试编译这 2 个来源。可以看到,它们在不同的包中,编译会失败。