父类:
1
package
com.quitgame.common;
2
3 public class Parent {
4 protected int i;
5}
2
3 public class Parent {
4 protected int i;
5}
同包子类
1
package
com.quitgame.common;
2
3 public class Son extends Parent {
4
5 /** *//**
6 * @param args
7 */
8 public static void main(String[] args) {
9 Son s = new Son();
10 s.i += 7; //OK,in the son class.
11
12 Parent p = new Parent();
13 p.i ++; //OK,in the same package.
14 }
15
16 public void testProtected(){
17 this.i ++; //OK,in the son class.
18 }
19}
2
3 public class Son extends Parent {
4
5 /** *//**
6 * @param args
7 */
8 public static void main(String[] args) {
9 Son s = new Son();
10 s.i += 7; //OK,in the son class.
11
12 Parent p = new Parent();
13 p.i ++; //OK,in the same package.
14 }
15
16 public void testProtected(){
17 this.i ++; //OK,in the son class.
18 }
19}
同包非子类
1
package
com.quitgame.common;
2
3 public class ClassInSamePackage {
4 /** *//**
5 * @param args
6 */
7 public static void main(String[] args) {
8 Son c = new Son();
9 c.i ++; //OK, in the same package .
10 }
11}
2
3 public class ClassInSamePackage {
4 /** *//**
5 * @param args
6 */
7 public static void main(String[] args) {
8 Son c = new Son();
9 c.i ++; //OK, in the same package .
10 }
11}
非同包子类
1
package
test;
2
3 import com.quitgame.common.Parent;
4
5 public class SonInAnotherPackage extends Parent {
6
7 /** *//**
8 * @param args
9 */
10 public static void main(String[] args) {
11 Parent p = new Parent();
12 //p.i ++; //error , not in the same package , not access througth this son class.
13 }
14
15 public void test(){
16 super.i ++; //OK,in the son class.
17 this.i ++; //OK,in the son class.
18 }
19
20}
21
2
3 import com.quitgame.common.Parent;
4
5 public class SonInAnotherPackage extends Parent {
6
7 /** *//**
8 * @param args
9 */
10 public static void main(String[] args) {
11 Parent p = new Parent();
12 //p.i ++; //error , not in the same package , not access througth this son class.
13 }
14
15 public void test(){
16 super.i ++; //OK,in the son class.
17 this.i ++; //OK,in the son class.
18 }
19
20}
21
public > protected > package > private
protected 除了可以在子类中访问,还可以在同包中访问。
这次IT大比武,栽在这个修饰符上了。