`

Java: Access Modifiers 访问修饰符

阅读更多
Controlling Access to Members of a Class
http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
引用
There are two levels of access control:
At the top level—public, or package-private (no explicit modifier).(类级访问修饰符只有public和default两个)
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 (packages are named groups of related classes—you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.


java中,若类和成员(变量、方法)前无访问修饰符,则为包访问权限;常称之为default、friendly或package-private。即:
default = friendly = package-private
访问修饰符从宽到严:
public  protected  default(friendly、package-private)  private


当前类同一包内子孙类其他包非子孙类(前三个之外的所有其他)
public
protected×
default(friendly、package-private)××
private×××
同一包内的可以认为是朋友;子孙类可以认为是子女;从default访问修饰符可以看出,相比子女,朋友更亲!
一个特殊的情况是接口:
接口中的
引用
All methods in an interface are implicitly public and abstract (but not final).
All fields in an interface are implicitly public, static and final.
在接口的方法/属性上使用上述修饰符都是多余的!建议直接省略,否则接口的方法写成 public String getXXX(), 整的好像接口的方法可以是非public似的!


访问修饰符不可以用在局部变量上,否则编译不通过。原因显而易见:局部变量的scope就是定义该局部变量的方法内,加访问修饰符是没有意义的。
http://wuaner.iteye.com/admin/blogs/1666376


抽象方法的访问修饰符只能是public或者protected。不能是private是因为抽象方法应该被重写,private使方法对子类不可见;语法上抽象方法可以不加访问修饰符(default访问权限),但最好不要这样做,因为会导致位于不同包下的抽象类之子类对抽象类的该抽象方法不可见。如下:
package lxg.oo.abstractclass;
public abstract class AbstractClassTest {
	abstract void aMothed();
}

package lxg.oo;
import lxg.oo.abstractclass.AbstractClassTest;
/**
 * 该实体类和其继承的抽象类在不同包下
 * 只能有两个选择:声明当前类也为抽象,或者修改抽象父类AbstractClassTest中抽象方法的访问修饰符为public|protected
 *
 */
public class ConcreteClassInAnotherPackage extends AbstractClassTest {

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics