书上对private修饰符号的解释是:
除了变量所在的类,其它任何类都不可以访问这个成员。
我做了一个试验:
//: c06:Chess.java
// Inheritance, constructors and arguments.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;class Game {
Game(int i) {
System.out.println("Game constructor");
}
private static int x1 = //a
print("我是private类型,为什么会被打印出来?");
static int print(String s) {
System.out.println(s);
return 47;
} //b a到b之间的代码是我后加的
}class BoardGame extends Game {
BoardGame(int i) {
super(i);
System.out.println("BoardGame constructor");
}
}public class Chess extends BoardGame {
private static Test monitor = new Test();
Chess() {
super(11);
System.out.println("Chess constructor");
}
public static void main(String[] args) {
Chess x = new Chess();
monitor.expect(new String[] {
"Game constructor",
"BoardGame constructor",
"Chess constructor"
});
}
} ///:~
我编译运行这段修改过后的代码,发现“我是private类型,为什么会被打印出来?”首先被打印了出来,这个情况使我摸不着头脑了,到底private的作用意义是什么啊?
除了变量所在的类,其它任何类都不可以访问这个成员。
我做了一个试验:
//: c06:Chess.java
// Inheritance, constructors and arguments.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import com.bruceeckel.simpletest.*;class Game {
Game(int i) {
System.out.println("Game constructor");
}
private static int x1 = //a
print("我是private类型,为什么会被打印出来?");
static int print(String s) {
System.out.println(s);
return 47;
} //b a到b之间的代码是我后加的
}class BoardGame extends Game {
BoardGame(int i) {
super(i);
System.out.println("BoardGame constructor");
}
}public class Chess extends BoardGame {
private static Test monitor = new Test();
Chess() {
super(11);
System.out.println("Chess constructor");
}
public static void main(String[] args) {
Chess x = new Chess();
monitor.expect(new String[] {
"Game constructor",
"BoardGame constructor",
"Chess constructor"
});
}
} ///:~
我编译运行这段修改过后的代码,发现“我是private类型,为什么会被打印出来?”首先被打印了出来,这个情况使我摸不着头脑了,到底private的作用意义是什么啊?
你如果在后继类中用print("x1= " + x1);看看结果,会出错.因为x1是父类的私有变量,子类中也不能访问.多看几遍书,就清楚了.