protected
的属性和方法可以在本包和子类访问 非同包的子类里面,不能直接使用父类,或者其它包的子类访问
例子:
// Base.java
package test.base; //创建包于文件夹下的文件夹base下
public class Base
{
int n[]=new int[10];
protected int testInt; //protected类型
public int publicInt; //public 类型
protected int getTestInt() { //public类型
return testInt;
}
}
//TestSamePackageSubClass.java 同包子类测试
package test.base;
/**
* Check the subclass in the same package
*/
public class TestSamePackageSubClass extends Base{
public void test1(){
Base b=new Base(); //Instance the base
b.publicInt=1; //Success to access the public member directly
b.testInt=1; //Success to access the protected member directly
b.getTestInt(); //Success to access the protected methoed directly
}
public void test2(){
publicInt=1; //Access the public member availably without instancing
testInt=1; //Access the protected member availably without instancing
getTestInt(); //Access the protected methoed availably without instancing
}
}
//结果: 同包子类可以直接访问父类里protected修饰的成员,而且不需要经过实例化
//测试同包的普通类
package test.base;
/**
* Check the normal class in the same package
*/
public class TestSamePackageNormal{
public void test1(){
Base b=new Base(); //Instance the base
b.publicInt=1; //Success to access the public member directly
b.testInt=1; //Success to access the protected member directly
b.getTestInt(); //Success the protected methoed directly
}
}
//结果:同包普通类可以直接访问其他protected修饰的成员
下面是不同包的普通类和子类测试,一个普通类,2个子类
//其他包里的子类
package test.sub1;
import test.base.Base;
/*
*The sub class in other package
**/
public class TestOtherPackageSubclass extends Base{
public void test1(){
Base b=new Base(); //Instance the base
b.publicInt=1; //Success to access the public member directly
b.testInt=1; //Fail to access the protected member directly
b.getTestInt(); //Fail to access the protected methoed directly
}
}
//结果:其他包里的子类可以不能直接访问父类里protected 修饰的成员
//测试在其他包里的普通类
package test.sub1;
import test.base.Base;
/*
*Check the normal class in other package
*
*
**/
public class TestOtherPackageNormal
{
public void test1(){
Base b=new Base(); //Instance the base
b.publicInt=1; //Success to access the public member directly
b.testInt=1; //Fail to access the protected member directly
b.getTestInt(); //Fail to access the protected methoed directly
}
}
//结果:其他包里的普通类不能直接访问protected 所修饰的成员
结论:
公共成员总能用
同包里,子类和普通类都能直接访问protected成员
不同包里,不能访问protected成员