Test code:
Packagecom.lky.h1; Public classBase {PrivateInteger ID; protectedString name; PublicInteger getId () {returnID; } Public voidsetId (Integer id) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"Base [id=" + ID + ", name=" + name + "]"; } }
Packagecom.lky.h1;Importorg.junit.Test;/*** @ClassName: test1* @Description: Test protect properties in the same package *@authoradministrator* @date October 13, 2015 **/ Public classTest1extendsbase{/*** @Title: Testbase * @Description: Access to the parent class itself*/@Test Public voidTestbase () {Base base=NewBase (); Base.setid (10);//base.id=9; private property within the same package cannot be accessed directlyBase.name= "Lky";//The protect property within the same package can be accessed directlySystem.out.println (base); } /*** @Title: Testexends * @Description: access to subclasses*/@Test Public voidtestexends () {test1 a=Newtest1 (); A.name= "Lky";//The Protect property is visible in subclasses and can be accessed directlyA.setid (10);//Private property is not visible in subclasses and cannot be accessed directlySystem.out.println (a); }}
Packagecom.lky.h2;Importorg.junit.Test;Importcom.lky.h1.Base; Public classTest2extendsBase {@Test Public voidTestbase () {Base base=NewBase (); //base.name= "Lky"; no direct access//base.id=10; no direct accessBase.setname ("Lky"); Base.setid (10); System.out.println (base); } @Test Public voidtestexends () {test2 a=Newtest2 (); A.name= "Lgh";//Direct access to//a.id = 10; //Cannot accessA.setid (10); System.out.println (a); }}
Summary: Assume that there is a class A and a Class B, and that a value attribute in Class A is protect
- If A and B are under the same package: in Class B, you can access the Protect property of a directly through a, experiment such as Test1 Testbase
- If A and B are under the same package, and B inherits from a: in Class B It is also possible to directly access the Protect attribute in a, experiment such as Test1 's testextends
- If A and B are not under the same package: in class B It is not possible to access the Protect property in a through a, that is, the property is not visible in class B, and experiments such as Test2 testbase
- If A and B are not under the same package and their B inherits from a: in Class B, you can access the Protect attribute in a, experiment such as Test2 Testextends
Summary of Protect attribute usage in Java