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
Java Class Accessibility
提问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
回答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 个来源。可以看到,它们在不同的包中,编译会失败。

