java类权限有四种,分别是public,protected,private和默认的权限。其中前三个权限是有明确定义的修饰符的,而默认的权限没有明确的修饰符(我们可以称之为default),在定义类,方法或者属性时,不用写任何修饰符。其中权限的作用域如下面表格所示:类权限作用域
Public权限
看下面一段代码
//在altsd.test包下有一个类Father
package altsd.test;
public class Father {
public int age;
int legs;
protected int eyes;
private int hhh;
private int getHhh(){
return hhh ;
}
}
//另一个包altsd.test1下有个Luren,与Father没有任何关系
package altsd.test1;
import altsd.test.Father;
public class Luren {
Father father = new Father();
public int getAge(){
return father.age;
}
}
我解释一下上面的代码,在Luren类中我们只返回了Father.age成员,不是说我不想返回Father的其他成员,是因为Luren和Father在不同的包,又不是父子关系,所以在Luren类中只能有访问Father的age成员,因为age的权限是public的。
总结:public权限的作用域是任何包下任何类都可以访问
protected权限
看下面的代码
另一个包altsd.test1下有个Child1,继承Father类
package altsd.test1;
import altsd.test.Father;
public class Child1 extends Father {
public int getAge(){
return super.age;
}
public int getEye(){
return super.eyes;
}
}
在这个类中,我们只能访问到父类的age和eyes成员,age的权限是public,这个在上面的代码中已经解释过了;eyes成员的权限是protected,因为Child1继承Father,虽然不在同一个包中,但也能访问eyes成员。
总结:protected权限的作用域是在只要有继承关系,就可以访问父类中的protected成员
default成员
看下面的代码
//在altsd.test包下有一个类Ancle,没有集成Father类
package altsd.test;
public class Ancle {
Father father = new Father();
public int getAge(){
return father.age;
}
public int getEye(){
return father.eyes;
}
public int getLegs(){
return father.legs;
}
}
在这个类中,Ancle可以访问Father中的age,eyes,legs成员,age是public,eyes是protected,legs是default。public和protected上面已经讲过。因为Ancle和Father是属于同一个包的,所以Ancle中可以访问Father的legs成员。
总结:默认权限(default)权限的作用域是同一个包下。
private权限
现在就只剩pravate权限了,只是我们所有的情况下都无法访问到hhh这个成员。我们看上面的权限作用域表格对private权限的定义:类本身。返回去看Father类中有一个getHhh()方法,这个方法中成功访问了hhh成员。现在应该能明白了吧。出去类本身可以访问private成员,一切引用类对象的作用域都访问不到private成员。