- 构造器初始化
初始化顺序
变量定义的先后顺序决定了初始化的顺序,即使变量定义散布于方法定义之间,它们仍旧会在任何方法(包括构造器)被调用之前得到初始化。
静态数据的初始化
static关键字不能应用于局部变量,无论创建多少个对象,静态数据都只占一份存储区域
静态初始化只有在必要时刻才会进行,静态初始化只在Class对象首次加载的时候进行一次
初始化的顺序是先静态对象(如果它们尚未因为前面的对象创建过程而被初始化),而后是“非静态”对象。
- 数组初始化
定义数组
类型后加[],如int[] i;或int i[]
数组初始化
int[] i = {1,2,3};
Integer[] a = new Integer[]{new Integer(1),2,new Integer(3)};
int[] j = new int[10];
Random rand = new Random();
int[] a = new int[rand.nextInt(20)];
Object[] obj = new Object[]{new Integer(1),new Float(2.0),new Double(3.0)};
Object[] objects = new Integer[]{1,2,3};
可变参数列表
class Test {
public static void main(String[] args) {
Test test = new Test();
test.printArray(1, new String("Hello"), new Float(2.0));
test.printArray(2, (Object[])new String[] {"Hello","World"});
test.printArray(0);
}
public void printArray(int num, Object... objects) {
System.out.print(num + " ");
for (Object object : objects) {
System.out.print(object + " ");
}
System.out.println();
}
}
-
枚举类型
由于枚举类型的实例是常量,按照命名惯例都用大写字母表示
枚举类型可以在switch语句内使用
编译器会创建ordinal()方法,用来表示某个特定的enum常量的声明顺序,以及static values()方法,用来按照enum常量的声明顺序,产生由这些常量值构成的数组。
class Test {
public enum Animal {
PIG, DOG, SHEEP, DUCK, WOLF
}
public static void main(String[] args) {
for (Animal animal : Animal.values()) {
System.out.println(animal.ordinal() + " : " + animal);
}
Animal animal = Animal.PIG;
System.out.print(animal);
}
}