Difference between static{} static code block and {} normal code block

Reprinted from: http://blog.csdn.net/aledavvv/article/details/16920743

The similarities and differences between static{} ( static code block ) and {} ( non-static code block )

The same point: they are all executed when the JVM loads the class and before the constructor is executed, and multiple classes can be defined in the class.

    Generally, some static variables are assigned in the code block.

The difference: static code blocks are executed before non-static code blocks ( static code block -> non-static code block -> constructor ) .

    Static code blocks are executed only once at the first new , and no longer executed after that, while non-static code blocks are executed every new

    Do it once. Non-static code blocks can be defined in ordinary methods ( but have little effect); static code blocks cannot.

example:

// Ordinary class public class  PuTong { public  PuTong(){ System.out.print(" Default constructor! -->"); } // Non-static code block {         System.out.print(" Non-static code block! -->"); } // Static code block static { System.out.print(" Static code block! -->"); } public static void  test(){ {             System.out.println(" In normal method The code block! "); }     } } // Test class public class  TestClass { /**

    

        

    

    
    
    

    

    
    
    
        

    

    
    
        


        






    

    
     
Distinguish between two executions of new static and non-static code blocks */ public static void  main(String[] args) { PuTong c1 =  new  PuTong(); c1.test();         PuTong c2 =  new  PuTong(); c2.test ();     } } /* The output of the operation is: static code block! --> Non-static code block! --> Default constructor! --> Code blocks in normal methods! Non-static code blocks! --> Default constructor! --> Code blocks in normal methods!
     

    

        

        

        

        








*/

In general, if some code must be executed when the project starts, you need to use a static code block, which is actively executed; it needs to be initialized when the project starts, and other objects will not be created without creating an object. When the program is called, you need to use a static method, and this code is executed passively.

The difference between the two is: static code blocks are executed automatically;

Static methods are only executed when they are called. 

What it does: Static code blocks can be used to initialize some of the most commonly used variables or objects in a project; static methods can be used as code that may need to be executed without creating an object.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326492810&siteId=291194637