楼上二位,《JAVA 2 核心技术》(卷一)中文版第123页,4.6.7初始化块一节中有这段代码:
class Employee
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee()
{
name = "";
salary = 0;
}
. . .
// must define before use in initialization block
private int id;
private static int nextId; // object initialization block
{
id = nextId;
nextId++;
}
. . .
private String name;
private double salary;
}
就是这段注释:// must define before use in initialization block,中文版是这么翻译的://必须在初始化块使用它之前定义。
是这本书的作者弄错了吗?
class Employee
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee()
{
name = "";
salary = 0;
}
. . .
// must define before use in initialization block
private int id;
private static int nextId; // object initialization block
{
id = nextId;
nextId++;
}
. . .
private String name;
private double salary;
}
就是这段注释:// must define before use in initialization block,中文版是这么翻译的://必须在初始化块使用它之前定义。
是这本书的作者弄错了吗?
// object initialization block
{
id = nextId;
nextId++;
}this is 类字段定义
private int id;
private static int nextId;when an instacne is constucted, it will run the 初始化块 first, and then constructor
so 类字段定义 must before 初始化块, or 初始化块 will not find the 类字段 and can not assign value to 类字段
you can use the following code to check it
public Employee()
{
name = "";
salary = 0;
//add code here
System.out.println(id); //print the value, if posible, please use class variant to check(such as change id to be Integer, or Float or String or self-define class)
System.out.println(nextid); //print the value
}
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public Employee()
{
name = "";
salary = 0;
}
. . .
// object initialization block
{
prt("初始化块");
id = nextId;
nextId++;
}
private static int prt(String s){
System.out.println(s);
return 0;
}
. . .
private int id;
private static int nextId = prt("initializing the private variable");
private String name;
private double salary;
}
你把程序改成这个,然后看系统的输出就知道到时是哪个先执行了。