代码块

尽可能不使用代码块

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);
    }
}

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

原文地址:https://www.cnblogs.com/da-peng/p/5119095.html