Block 18

1. The code block structure

--- {} may be in any configuration method execution priority, call arbitrary constructor configured to be executed in code blocks outside the class methods

public  class Public {
     public  static  void main (String [] args) { 
        Test P = new new Test (); 
        System.out.println (p.age + p.name);     
        Test P2 = new new Test (. 11, "Xuwang Jun" ) ; 
        System.out.println (p.age + p.name);     
    } 
    } // endclass 

class Test {
     int Age; 
    String name; 
    // configured block
     // call the constructor are any default execution block configured
     // priority code block configured to perform any of the constructor
     //Can be configured to block the initial value of the attribute assigned to the calling method 
    {
     the this .age =. 11 ;
     the this .name = "Xu Wang riding" ; 
    System.out.println ( "configuration code block" ); 
    } 

    // no constructor parameters 
    public Test () 
    { 
        System.out.println ( "no-argument constructor" ); 
    } 
    // have argument constructor 
    public Test ( int Age, String name) 
    { 
        System.out.println ( "there argument constructor" ); 
    } 
    } // endclass

result

Configuration block
no argument constructor
11 Xu Wang riding
configuration code block
with a constructor parameter
11 ride Xu Wang

 

2. The partial block (block method)

In the method --- to control the variable life cycle to improve the utilization code

public  class Public {
     public  static  void main (String [] args) {
         int J =. 1 ;
         // topical (Method) block
         // main use is as a method for very long time, I do not want to be frequently used variables rapid clearance, but not always stored in the stack
         // to control the life cycle of the variable 
        {
            int I = 2 ; 
           System.out.println (I); 
        } 
    } 
} // endclass

 

Guess you like

Origin www.cnblogs.com/xuwangqi/p/11082482.html