1. 类成员的访问控制修饰符protected表示该类所属包内的类或该类的派生类可以访问protected成员。
1.2 针对protected成员,有一个容易误解的地方,请看下面的代码
<pre name="code" class="java">//Base.java
package test;
public class Base {
protected int i=0;
}
//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成员
}
}
1.3 通过以上代码,可以得出结论:在生成派生类时,派生类可以继承基类的protected成员,这个继承的protected成员在派生类内部是可以访问的,但是在派生类内部无法直接访问基类对象的protected成员。
1.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 {
}
2.虽然protected域对所有子类都可见。但是有一点很重要,子类只能在自己的作用范围内访问自己继承的那个父类protected域,而无法到访问别的子类(同父类的亲兄弟)所继承的protected域。 总之,当B
extends A的时候,在子类B的作用范围内,只能调用本子类B定义的对象的protected方法(该方法从父类A中继承而来)。而不能调用其他A类对象的protected 方法。