一、Java访问权限控制
1)在类的内部都可以访问到四种权限
package com.learn.permission;
public class TestPermission {
private String privateStr = "private";
protected String protectedStr = "protected";
public String pulicStr = "public";
String packageStr = "package";
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestPermission test = new TestPermission();
System.out.println(test.pulicStr);
System.out.println(test.packageStr);
System.out.println(test.protectedStr);
System.out.println(test.privateStr);
}
}
2)同一包内不同类,private不可见
package com.learn.permission;
public class TestInPackage {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestPermission test = new TestPermission();
System.out.println(test.pulicStr);
System.out.println(test.packageStr);
System.out.println(test.protectedStr);
// System.out.println(test.privateStr); //private is not visible in different class of same pacakge
}
}
3)同一包里子类,private不可见
package com.learn.permission;
public class TestPermissionExtends extends TestPermission {
public static void main(String[] args){
TestPermissionExtends test = new TestPermissionExtends();
System.out.println(test.pulicStr);
System.out.println(test.packageStr);
System.out.println(test.protectedStr);
//after extend , the private field or method is not available
// System.out.println(test.privateStr);
}
}
4) 不同包非子类,只有public可见
package com.learn.chapter1;
import com.learn.permission.TestPermission;
public class TestOutPackage {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestPermission test = new TestPermission();
System.out.println(test.pulicStr);
//outside the package , only the public is available
// System.out.println(test.packageStr);
// System.out.println(test.protectedStr);
// System.out.println(test.privateStr);
}
}
5)不同包里子类,只有public和protected可见
package com.learn.chapter1;
import com.learn.permission.TestPermission;
public class TestPermissionExtend extends TestPermission {
public static void main(String[] args){
TestPermissionExtend test = new TestPermissionExtend();
System.out.println(test.pulicStr);
// System.out.println(test.packageStr);
System.out.println(test.protectedStr);
//after extend , the private field or method is not available
// System.out.println(test.privateStr);
}
}
总结:
Public:对任意类可见
protected :与包访问权限类似,只是被继承的时候可见,这个时候相当于private,不过仍可以继承可见
包访问权限:只对当前包可见
private :只对当前类可见