Controlling Access to Members of a Class
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
| no modifier(未指定默认default) | 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.
Let's look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.

Classes and Packages of the Example Used to Illustrate Access Levels
The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.
| Modifier | Alpha | Beta | Alphasub | Gamma |
|---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
| no modifier | Y | Y | N | N |
private | Y | N | N | N |
本文探讨了类成员的访问级别,包括public、protected、private和无修饰符,解释了这些级别如何影响不同类、包和子类的访问权限。通过实例分析,理解如何在编程中决定方法和变量的可见性,以及跨包、继承和全局访问的规则。
299

被折叠的 条评论
为什么被折叠?



