zoukankan      html  css  js  c++  java
  • java代码块

    一、构造代码块

    1、执行顺序

         每次new 对象时执行,优先于构造函数的执行。

    2、代码:

     1 class test {
     2     
     3     //构造函数
     4     public test() {
     5         System.out.println("构造函数代码块");
     6     }
     7     
     8     //有参数构造函数
     9     public test(String str) {
    10         System.out.println("构造函数代码块" + str);
    11     }
    12     
    13     //构造代码块
    14     {
    15         System.out.println("构造代码块");
    16     }
    17     
    18 }
    19 
    20 public class hello {
    21     
    22     public static void main(String[] args) {
    23         System.out.println("主代码块");
    24         test h = new test();
    25         test hh = new test("又创建一个对象");
    26     }
    27 }

    3、执行结果:

    二、静态代码块

    1、执行顺序

         优先于构造代码块,构造函数执行

    2、作用

         给静态成员初始化

    3、代码

    public class hello {
        
        public static void main(String[] args) {
            System.out.println("主代码块");
            test h = new test();
            test hh = new test("又创建一个对象");
        }
    }
    
    class test {
        private static int num;
        
        //构造函数
        public test() {
            System.out.println("构造函数代码块");
        }
        
        //有参数构造函数
        public test(String str) {
            System.out.println("构造函数代码块" + str);
        }
        
        //构造代码块
        {
            System.out.println("构造代码块");
        }
        
        //静态代码块
        static {
            num = 1;
            System.out.println("静态代码块");
            System.out.println("num=" + num);
        }
        
    }

    4、结果

  • 相关阅读:
    sed匹配多行并替换其中的内容
    sysbench 安装、使用和测试
    linux inode号已满的解决办法
    Linux双网卡绑定
    es安装
    kibana安装
    filebeat
    Codeforces 464E The Classic Problem (最短路 + 主席树 + hash)
    Codeforces 1137C Museums Tour (强连通分量, DP)
    HDU 4921 Map(状态压缩)
  • 原文地址:https://www.cnblogs.com/liji275137657/p/3723445.html
Copyright © 2011-2022 走看看