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

    尽可能不使用代码块

    1.普通代码块

    如果说一个代码块写在了方法里面,就叫普通代码块

    public class Test{
        public static void main(String args[]){
            if( true ){
                int num = 10 ;
            }
            int num = 100 ;
        }
    }
    此程序可以正常编译通过。

    如果去掉了if(true)则 大括号里面的东西就叫做代码块。

    代码块是为了防止变量过多时候产生的变量重名,对一个方法的代码分割,在以后编写代码的时候,一个方法里的代码不要写的很长。所以一般不需要写代码块。

    2.构造块

    如果说将一个代码块写在了一个类里面那么这个代码块就是构造块。

    class Book{
        public Book(){
            System.out.println("[A]") ;
        }
        {
            System.out.println("B") ;
        }
    }
    public class Test{
        public static void main(String args[]){
            Book b1 = new Book() ;
        }
    }
    当程序运行的时候,构造块执行优先于构造方法的执行,所以输出的结果是  B   A。

    3.静态块

    如果一个代码块使用了static进行定义的话,那么就成为静态块。分两种情况

    (1)非主类中使用

    class Book{
        public Book(){
            System.out.println("[A]") ;
        }
        {
            System.out.println("B") ;
        }
        static{
            System.out.println("c") ;
        }
    }
    public class Test{
        public static void main(String args[]){
            Book b1 = new Book() ;
            Book b2 = new Book() ;
            Book b3 = new Book() ;
            Book b4 = new Book() ;
        }
    }
    

     静态块优先于构造块执行,而且不管有多少个实例都只执行一次。

    他的只要功能是给类中的static属性初始化的。

    class Book{
        static String msg ;
        public Book(){
            System.out.println("[A]") ;
        }
        {
            System.out.println("B") ;
        }
        static{
            msg = "Hello".substring(2) ;
            System.out.println("c") ;
        }
    }
    public class Test{
        public static void main(String args[]){
            Book b1 = new Book() ;
            Book b2 = new Book() ;
            Book b3 = new Book() ;
            Book b4 = new Book() ;
            System.out.println(Book.msg) ;
        }
    }
    

     (2)主类中

    public class Test{
        static{
            System.out.println("****") ;
        }
        public static void main(String args[]){
            System.out.println(1);
        }
    }
    

     代码块的执行优先于主方法。

  • 相关阅读:
    Min_25 筛 学习笔记
    UOJ#172. 【WC2016】论战捆竹竿 字符串 KMP 动态规划 单调队列 背包
    Codeforces 715B. Complete The Graph 最短路,Dijkstra,构造
    UOJ#407. 【IOI2018】狼人 Kruskal,kruskal重构树,主席树
    UOJ#218. 【UNR #1】火车管理 线段树 主席树
    Codeforces 1045E. Ancient civilizations 构造 计算几何 凸包
    Codeforces 947F. Public Service 构造
    Pop Star 1.2.5
    TopCoder SRM704 Div1 800 构造
    Codeforces 1109E. Sasha and a Very Easy Test 线段树
  • 原文地址:https://www.cnblogs.com/da-peng/p/5119095.html
Copyright © 2011-2022 走看看