对象,类属性初始化,

1-对象属性初始化

对象属性初始化有3种
1. 声明该属性的时候初始化 
2. 构造方法中初始化
3. 初始化块
代码比较复制代码
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 //构造方法中初始化
         
     }
     
}

2-类属性初始化

类属性初始化有2种
1. 声明该属性的时候初始化
2. 静态初始化块
代码比较复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package  charactor;
 
public  class  Hero {
     public  String name;
     protected  float  hp;
     float  maxHP;
     
     //物品栏的容量
     public  static  int  itemCapacity= 8 //声明的时候 初始化
     
     static {//标注static,表示块中初始化的是类属性
         itemCapacity =  6 ; //静态初始化块 初始化
     }
     
     public  Hero(){
         
     }
     
     public  static  void  main(String[] args) {
         System.out.println(Hero.itemCapacity);
     }
     
}

3-相关顺序

package  charactor;
  
public  class  Hero {
     public  String name =Hero.getName( "属性声明" ) ;//1
      
     public  Hero(){
         name = Hero.getName( "构造方法" );//3
     }
     {
         name = Hero.getName( "初始化块" );//2
     }
     
     public  static  String getName(String pos){
         String result=  "name " +pos;
         System.out.println(result);
         return  result;
     }
     
     public  static  void  main(String[] args) {
         new  Hero();
     }
     
}

猜你喜欢

转载自blog.csdn.net/whiteleaf3er/article/details/80903983