2019-05-24 java学习日记

面向对象

代码块的概述与分类

在java中,使用 { } 括起来的被称为代码块

代码块分类:

根据其位置和声明的不同,可以分为局部代码块,构造代码块,静态代码块,同步代码块(多线程讲解)

常见代码块的应用:

局部代码块:

  在方法重出现,限定变量的生命周期,及早释放,提高内存利用率

构造代码块(初始化块):

  在类中方法外出现;多个构造方法中相同的代码存放在一起,
  每次跳用构造都执行,并且在构造方法前执行

静态代码块:

  1,在类中方法外出现,加了static修饰

  2,在类中方法外出现,并加上static修饰;用于给类进行初始化,在加载的时候执行,并且只执行一次

  3,一般用于加载驱动

 1 class Demo1_Code {
 2     public static void main(String[] args) {
 3         {
 4             int x = 10;                        //限定变量的声明周期
 5             System.out.println(x);
 6         }
 7         
 8         Student s1 = new Student();
 9         System.out.println("---------------");
10         Student s2 = new Student("张三",23);
11     
12     }
13 
14     static {
15         System.out.println("我是在主方法类中的静态代码块");
16     }
17 }
18 
19 class Student {
20     private String name;
21     private int age;
22 
23     public Student(){
24         //study();
25         System.out.println("空参构造");
26     }                                    //空参构造
27 
28     public Student(String name,int age) {//有参构造
29         //study();
30         this.name = name;
31         this.age = age;
32         System.out.println("有参构造");
33     }
34 
35     public void setName(String name) {
36         this.name = name;
37     }
38 
39     public String getName() {
40         return name;
41     }
42 
43     public void setAge(int age) {
44         this.age = age;
45     }
46 
47     public int getAge() {
48         return age;
49     }
50 
51     {    //构造代码块:每创建一次对象就会执行一次,优先于构造函数执行
52         //System.out.println("构造代码块");
53         study();
54     }
55 
56     public void study() {
57         System.out.println("学生学习");
58     }
59 
60     static {                                    
61         System.out.println("我是静态代码块");    
62                 //随着类加载而加载,且只执行一次
63                //作用:用来给类进行初始化,一般用来加载驱动
64               //静态代码块是优先于主方法执行
65     }
66 }
例子
 1 class Student {
 2     static {
 3         System.out.println("Student 静态代码块");
 4     }
 5     
 6     {
 7         System.out.println("Student 构造代码块");
 8     }
 9     
10     public Student() {
11         System.out.println("Student 构造方法");
12     }
13 }
14 
15 class Demo2_Student {
16     static {
17         System.out.println("Demo2_Student静态代码块");
18     }
19     
20     public static void main(String[] args) {
21         System.out.println("我是main方法");
22         
23         Student s1 = new Student();
24         Student s2 = new Student();
25     }
26 }
例子2

猜你喜欢

转载自www.cnblogs.com/Sherwin-liao/p/10919780.html