初始化数据域的方法:
1、在构造器中设置只进行初始化
2、在声明中直接赋值进行初始化
3、初始化块(包括静态域初始化块 和 初始化块)
在一个类的声明中可以包含多个代码块,只要构造类的对象,这些快就会被执行。
package 第3章;
import java.util.*;
public class 第3章a
{
public static void main (String[] args)
{
Employee hello=new Employee();
System.out.println(hello.getName()+" and "+hello.getSalary());
Employee well=new Employee("what?",11);
System.out.println(well.getName()+" aaa "+well.getSalary());
}
}
class Employee
{
private static int nextId;
private int id;
private String name;
private double salary;
{
id=nextId;
++nextId;
}
public Employee(String a_name,double a_salary)
{
name=a_name;
salary=a_salary;
}
public Employee()
{
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
}
静态初始化块+nextId随机
package 第3章;
import java.util.*;
public class 第3章a
{
public static void main (String[] args)
{
Employee hello=new Employee();
System.out.println(hello.getId()+" "+hello.getNextId());
Employee well=new Employee("what?",11);
System.out.println(well.getId()+" "+well.getNextId());
Employee well2=new Employee("what?",11);
System.out.println(well2.getId()+" "+well.getNextId());
}
}
class Employee
{
private static int nextId;
private int id;
private String name;
static
{
Random yoyo=new Random();
nextId=yoyo.nextInt(10); //nextId 已经被定义过了,所以如果在此定义,就会隐藏nextId字段
}
// System.out.println(nextId);
private double salary;
{
id=nextId;
++nextId;
}
public Employee(String a_name,double a_salary)
{
name=a_name;
salary=a_salary;
}
public Employee()
{
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public int getNextId()
{
return nextId;
}
}
run:
7 8
8 9
9 10
成功构建 (总时间: 0 秒)
在这个机制中,无论使用哪个构造器构造对象,nextId都在初始化块中被初始化,然后才能运行构造器的主体部分。
这种机制不是必须的,也不常见,通常会将初始化代码直接放在构造器中