对象属性初始化
- 声明的同时初始化
- 块初始化(声明后初始化)
- 通过构造方法初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package charactor; public class Hero { public String name = "some hero"; protected float hp; float maxHP; { maxHP = 200; } public Hero(){ hp = 100; } }
|
注意:最后进行的是通过构造方法进行的初始化,需要在创建对象的时候才开始初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package ChuShiHua;
public class Hero { public String name = "some hero"; { System.out.println("声明时初始化:"+name); }
public Hero() { name = "one hero"; System.out.println("构造方法中初始化:" + name); }
{ name = "the hero"; System.out.println("块初始化:" + name); } }
|
创建对象,查看输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package ChuShiHua;
public class Test { public static void main(String[] args){ Hero hero = new Hero(); } }
|
因此初始化顺序为:声明时初始化->块初始化->构造方法中初始化