代码块概述
代碼塊:在Java中,使用{}括起來的代碼被稱為代碼塊。
根據(jù)其位置和聲明的不同,可以分為:
局部代碼塊:局部位置,用于限定變量的生命周期。
構造代碼塊:在類中的成員位置,用{}括起來的代碼。每次調(diào)用構造方法執(zhí)行前,都會先執(zhí)行構造代碼塊。作用:可以把多個構造方法中的共同代碼放到一起,對對象進行初始化。
靜態(tài)代碼塊:在類中的成員位置,用{}括起來的代碼,只不過它用static修飾了。作用:一般是對類進行初始化。
相關面試題:
靜態(tài)代碼塊,構造代碼塊,構造方法的執(zhí)行順序?
靜態(tài)代碼塊 --> 構造代碼塊 --> 構造方法
靜態(tài)代碼塊:只執(zhí)行一次
構造代碼塊:每次調(diào)用構造方法都執(zhí)行
class Student {static {System.out.println("Student 靜態(tài)代碼塊");}{System.out.println("Student 構造代碼塊");}public Student() {System.out.println("Student 構造方法");} }class StudentDemo {static {System.out.println("StudentDemo 靜態(tài)代碼塊");}public static void main(String[] args) {System.out.println("這是main方法");Student s1 = new Student();Student s2 = new Student();} }
上述程序執(zhí)行結果為:
StudentDemo 靜態(tài)代碼塊
這是main方法
Student 靜態(tài)代碼塊
Student 構造代碼塊
Student 構造方法
Student 構造代碼塊
Student 構造方法
總結
- 上一篇: 2021年中国银行存款利率表一览表?20
- 下一篇: 白金信用卡不开卡收取年费吗 了解清楚才能