基类代码:包为com.fu
- package com.fu;
- public class Base {
- protected int protectedInt; //protected成员
- public int publicInt; //public 成员
- protected int getProtectedInt(){
- return protectedInt;
- }
- protected static int staticProtectInt;
- private int privateInt;
- public static void main(String[] args) {
- Base b=new Base();
- b.privateInt=5;
- }
- }
不同包内派生类:com.zi
- package com.zi;
- import com.fu.Base;
- public class TestOtherPackageSubClass extends Base {
- public void test() {
- Base b = new Base(); // 使用基类
- b.publicInt = 0; // 可以访问
- <span style="color:#FF0000;">//b.protectedInt=3; // 访问protected的属性失败
- //b.getProtectedInt(); // 访问protected的方法失败</span>
- Base.staticProtectInt=9;
- }
- public void test2() {
- <span style="color:#FF0000;">//privateInt =6; //访问父类的私有-出错</span>
- publicInt = 0; // 可以访问
- protectedInt = 2; // 直接用父类的属性-成功
- super.protectedInt=4;
- getProtectedInt(); // 直接用父类的方法-成功
- System.out.println("getProtectedInt-test2:"+getProtectedInt());
- protectedInt = 22; // 直接用父类的属性-成功
- Base.staticProtectInt=10;
- super.getProtectedInt(); // 直接用父类的方法-成功
- System.out.println("getProtectedInt-test2:"+getProtectedInt());
- }
- public void test3(){
- TestOtherPackageSubClass t=new TestOtherPackageSubClass();
- t.protectedInt=6;
- t.getProtectedInt();
- System.out.println("getProtectedInt-test3:"+t.getProtectedInt());
- }
- public static void main(String[] args) {
- TestOtherPackageSubClass t=new TestOtherPackageSubClass();
- t.test2();
- System.out.println(Base.staticProtectInt);
- }
- }
运行结果为:
getProtectedInt-test2:4
getProtectedInt-test2:22
10
从运行结果 看出 test2 中 不管有没有写super.protectInt,还是直接protectInt 都是指向父类的成员。从这可以看出 不在同一包的子类可以直接(未实例化)访问父类数据成员。
如果把这个Base.staticProtectInt=10; 去掉的话, Base.staticProtectInt输出结果为0。因为test()方法没有调用不会设为9。
同一包内子类代买 com.fu
- package com.fu;
- import com.zi.TestOtherPackageSubClass;
- public class TestSamePackageSubClass extends Base {
- public void test() {
- Base b = new Base(); // 使用基类
- b.publicInt = 0; // 可以访问
- b.protectedInt=3; // 访问protected的属性-成功
- b.getProtectedInt(); // 访问protected的方法-成功
- }
- public void test2() {
- publicInt = 0; // 可以访问
- protectedInt = 2; // 直接用父类的属性-成功
- Base.staticProtectInt=9;
- System.out.println("getProtectedInt-test2:"+getProtectedInt());
- }
- public void test3(){
- TestOtherPackageSubClass t=new TestOtherPackageSubClass();
- t.protectedInt=6;
- System.out.println("getProtectedInt-test3:"+t.getProtectedInt());
- }
- public static void main(String[] args) {
- TestSamePackageSubClass t=new TestSamePackageSubClass();
- t.test2();
- t.test3();
- }
- }
如果同一包内的话可以通过 b.protectedInt 访问了。
同一包内非派生类:
- package com.fu;
- public class TestSamePackageNotSubClass {
- public static void main(String[] args) {
- Base b = new Base(); // 使用基类
- b.publicInt = 0; // 可以访问 -成功
- b.protectedInt=3;
- System.out.println(b.getProtectedInt());
- }
- }
同一包子类可以直接或实例化(new)访问protedted成员,普通类可以实例化(new)访问protedted成员不可直接访问,而不属于同一包内的派生类中只能直接使用基类super. protedted成员 或者protedted成员,而不能通过 实例化访问(new) 访问。