`

[#0x0001] initializer

    博客分类:
  • Java
 
阅读更多

  A block-formed initializer can be appended after the fields declared.
  If the fields are static, the initializer can also be static too, which means it's only executed once. If the initializer is not static, it will be executed as many times as the class constructor will be, even if the fields are static.
  The non-static fields can not be initialized in a static intializer.

//@file Bookshelf.java

class Book   
{   
    Book(int id)   
    {   
        System.out.println("This is book No." + id);   
    }   
}   
  
class Bookshelf   
{   
    // case 1:   
    /**  
    Book b1;  
    Book b2;   
    {  
        b1 = new Book(1);  
        b2 = new Book(2);  
    }  
    */  
    //output:   
    //This is book No.1   
    //This is book No.2   
    //This is book No.1   
    //This is book No.2   
  
    //case 2:   
    static Book b1;   
    static Book b2;   
    static    
    {   
        b1 = new Book(1);   
        b2 = new Book(2);   
    }   
    //output:   
    //This is book No.1   
    //This is book No.2   
  
    //case 3:   
    /**  
    static Book b1;  
    static Book b2;  
    {  
        b1 = new Book(1);  
        b2 = new Book(2);  
    }  
    */  
    //output:   
    //This is book No.1   
    //This is book No.2   
    //This is book No.1   
    //This is book No.2   
  
    //case 4:   
    /**  
    Book b1;  
    Book b2;  
    static   
    {  
        b1 = new Book(1);  
        b2 = new Book(2);  
    }  
    */  
    //output: error   
}   
  
class InitBlockTest   
{   
    public static void main(String[] arg)   
    {   
        new Bookshelf();   
        new Bookshelf();   
    }   
}

 

(9月4号补充)

  initializer不一定非要是初始化成员,在initializer内部其实是可以随便写的,像这样也可以:

class Test
{
	//static
	{
		System.out.println("pass");
	}
}

public class InitializerTest
{
	public static void main(String[] args)
	{
		new Test();
		new Test();
	}
}

//output
/*
	pass
	pass
*/

  另:在声明field的时候,常常会当场初始化field,这个称为variable intializer (更倾向于将声明field的表达式右值称为variable initializer)。根据field是否static及初始化是否调用了static方法,variable initializer有的属于class行为,有的属于object行为。static initializer完全属于class行为。

 

(2009年09月04日归纳:[#0x0023])

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics