day08--static-静态代码块的使用

This commit is contained in:
2025-12-30 16:27:19 +08:00
parent 4073285850
commit 7b79dc69c0
2 changed files with 41 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
package com.inmind.static02;
/*
静态代码块:
定义在成员位置使用static修饰的代码块{ }。
位置:类中方法外。
执行随着类的加载而执行且执行一次优先于main方法和构造方法的执行。
格式:
static{
java语句;
}
静态代码块的作用:在程序运行之前,就进行一些操作,常用于对静态变量的初始化操作,后期工作中常用于对配置文件的值赋值操作
*/
public class Demo11 {
static int num = 10;
String str;
static{
System.out.println("静态代码块执行了");
if (1 > 0) {
num = 200;
} else {
num = 300;
}
num = 100;
}
public static void main(String[] args) {
System.out.println(num);
System.out.println("程序开始");
//创建1个学生
Student student = new Student();
System.out.println("程序结束");
}
public void test(){
System.out.println("呵呵哒");
}
}

View File

@@ -21,6 +21,7 @@ public class Student {
public Student() { public Student() {
System.out.println("学生类的无参构造方法调用了");
} }
public Student(int id, int age, String name) { public Student(int id, int age, String name) {
this.id = id; this.id = id;