2022.3.29 代码块

代码块

 1  package com.oop.demo09;
 2  3  public class Person {
 4  5      {
 6          //代码块,匿名代码块,程序在执行时不能主动调用
 7          //在创建对象时自动创建,在构造器之前
 8          //作用:赋初值
 9          System.out.println("匿名代码块");
10      }
11 12      static {
13          //静态代码块,类加载就执行,只执行一次
14          System.out.println("静态代码块");
15      }
16 17      public Person() {
18          System.out.println("构造器");
19      }
20 21      public static void main(String[] args) {
22          //静态代码块,类加载就执行,只执行一次
23          //每次创建对象都会执行匿名代码块,构造器
24          Person person1 = new Person();
25          System.out.println("===========================");
26          Person person2 = new Person();
27      }
28  }
29  /*
30  静态代码块
31  匿名代码块
32  构造器
33  ===========================
34  匿名代码块
35  构造器
36   */

 

 

posted @ 2022-03-29 15:51  暴躁C语言  阅读(21)  评论(0)    收藏  举报