一、代码块:                                        

构造代码块------类中方法的外面;每次调用构造方法都执行;

静态代码块------类中方法的外面,括号前加上static;只执行一次,随着类的加载而执行;


转转转!!java基础一些静态代码块等知识点转转转!!java基础一些静态代码块等知识点

 static代码块、构造代码块,自己写的做实验的小例子:

 1 public class TestStatic{
 2     public static void main(String args[]){
 3         TestBlock t1 = new TestBlock();
 4         System.out.println(t1);
 5         System.out.println("-------------------------");
 6         
 7         TestBlock t2 = new TestBlock(50);
 8         System.out.println(t2);
 9         System.out.println("-------------------------");
10         
11         TestBlock t3 = new TestBlock(11, "lisi");
12         System.out.println(t3);
13     }
14 }
15 
16 class TestBlock{
17     
18     int id = 100;
19     String sex;
20     String name;
21     
22     //static block, when the class load, execute it;
23     static {
24         System.out.println("init TestBlock....");
25     }
26     
27     //constructor block, when constructor method execute, this block execute
28     {
29         sex = "male";
30         name = "zhangsan";
31         System.out.println("init begin constructor...");
32     }
33     
34     TestBlock(){
35         
36     }
37     
38     TestBlock(int id){
39         this.id = id;
40     }
41     
42     TestBlock(int id, String name){
43         this.id = id;
44         this.name = name;
45     }
46     
47     public String toString(){
48         return "id: " + id + " sex: " + sex + " name:" + name;
49     }
50     
51 }
View Code

相关文章:

  • 2021-11-20
  • 2021-11-07
  • 2018-12-17
  • 2021-11-13
  • 2022-02-09
  • 2022-03-02
  • 2022-01-02
  • 2022-12-23
猜你喜欢
  • 2021-07-21
  • 2022-01-21
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-24
相关资源
相似解决方案