Posted on 2006-07-06 18:13
負人博客 閱讀(324)
評論(0) 編輯 收藏 所屬分類:
JAVA技術(shù)
對于protected關(guān)鍵字經(jīng)常在使用中弄混,特寫一小例進行測試
Protected方法或?qū)傩岳樱?/p>
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定義的東西在不同包內(nèi)不能訪問,只有繼承的子類可以訪問