protectedの詳細について

3109 ワード

最近、私はSCJPをひどく見て、ほほほ、だから記録は比較的にこまごましていて、ははは----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1
2
3
4
5
6
7
package scjp;

 

public class Parent {

 

	protected int x=9;//protected access

 

}


コードは変数xをprotectedとして宣言し、SCJPパッケージ内の他のすべてのクラスが変数にアクセスしたり、パッケージ外の任意のサブクラスが継承したりすることができます.次に、別のパッケージにサブクラスを作成し、変数x(サブクラスが継承する変数)を使用してみます.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package other;

import scjp.Parent;;

 

public class Child extends Parent{

 

	public void testIt(){

		System.out.println("x is "+x);

	}

	/**

	 * @param args

	 */

	public static void main(String[] args) {

		Child cd=new Child();

		cd.testIt();

		

//		Parent p=new Parent();

//		System.out.println("x in parent is "+p.x);

	}

}


上の文は完全にコンパイルでき、正しい結果を出力できます.x is 9ですが、コメントの2行を削除すると、コンパイルできません.実行結果は次のとおりです.
1
2
3
4
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

	The field Parent.x is not visible

 

	at other.Child.main(Child.java:17)


これは、パッケージ外の他の非サブクラスではprotected変数が表示されないことを十分に示している.