//TestProtected.java import test.Base; public class TestProtected extends Base { public static void main(String [] args) { TestProtected tp = new TestProtected(); System.out.println(tp.i); // Correct , 派生类中继承了基类的protected 成员,派生类中能访问派生类对象所继承的protected 成员 Base bbb = new Base(); System.out.println(bbb.i); //Error , 不能访问基类对象的protected 成员 } } 3. 通过以上代码,可以得出结论:在生成派生类时,派生类可以继承基类的protected成员,这个继承的protected成员在派生类内部是可以访问的,但是在派生类内部无法直接访问基类对象的protected成员。 4. 更进一步,一种派生类内部只能访问该种派生类的对象继承的基类protected成员,不能访问基类的其他派生类对象继承的基类protected成员。请看代码: //Base.java package test; public class Base { otected int i=0; }
//TestProtected.java import test.Base; public class TestProtected extends Base { public static void main(String [] args) { TestProtected tp1 = new TestProtected(); derive tp2 = new Derive(); System.out.println(tp1.i); // correct System.out.println(tp2.i); //Compile error } }
class Derive extends Base { } from: http://blog.itpub.net/post/2552/11703