feat(class36): 代码块的使用

- 新增 Test 类,包含静态代码块和普通代码块
-静态代码块用于初始化类级别的资源,如扑克牌数组- 普通代码块用于初始化对象的实例资源
-通过 main 方法演示代码块的执行顺序和作用
This commit is contained in:
2025-07-28 02:35:43 +08:00
parent 3c323deb51
commit 406787c2a2
2 changed files with 59 additions and 0 deletions

30
src/class31/Test.java Normal file
View File

@@ -0,0 +1,30 @@
package class31;
public class Test {
public static void main(String[] args) {
People p = new Student();
Driver d = new Student();
BoyFriend b = new Student();
Driver a =new Student();
BoyFriend bf = new Student();
// br.drive(); 错误, BoyFriend接口没有drive方法
a.drive();
}
}
interface Driver{
void drive();
}
interface BoyFriend{}
class People{}
class Student extends People implements Driver,BoyFriend{
@Override
public void drive() {
}
}

29
src/class36/Test.java Normal file
View File

@@ -0,0 +1,29 @@
package class36;
import java.util.Arrays;
public class Test {
public static String[] cards = new String[46];
static {
// 静态代码块 static修饰 属于类 与类一起加载运行 只运行一次
System.out.println("静态代码块");
cards[0] = "大王";
cards[1] = "小王";
for (int i = 2; i < 15; i++) {
cards[i] = i + "方片";
cards[i + 13] = i + "梅花";
cards[i + 26] = i + "草花";
cards[i + 31] = i + "黑桃";
}
}
//初始化对象的实例资源,随实例创建而运行
{
System.out.println("普通代码块");
}
public static void main(String[] args) {
// 目标:认识代码块,搞清楚代码块的作用
System.out.println(Arrays.toString(cards));
new Test();
}
}