Posted on 2006-07-06 18:13
負人博客 閱讀(319)
評論(0) 編輯 收藏 所屬分類:
JAVA技術
對于protected關鍵字經常在使用中弄混,特寫一小例進行測試
Protected方法或屬性例子:
Package com.first;
Public class Test1 {
?Protected String a;
Protected void test() {
? System.out.println(“it is a test”);
}
}
package com.second;
import com.first.*;
public class Test2 extends Test1 {
?Test1 test1 = new Test1();
Test2 test2 = new Test2();
test1.a = “test”;//錯誤
test2.a = “test”; //正確
test1.test();//錯誤
test2.test();//正確
}
///原因,protected定義的東西在不同包內不能訪問,只有繼承的子類可以訪問