题目:
编写一个类,拥有两个静态字符串域,其中一个在定义处初始化,另一个在静态块中初始化。现在,加入一个静态方法用以打印出两个字段值。请证明它们都会在被使用之前完成初始化动作。
解答:
import java.util.*;
class fourteen {
static char a = 'a';
static char b;
static {
b = 'b';
}
}
public class chapterFive {
public static void main(String[] args){
fourteen f = new fourteen();
System.out.println(f.a);
System.out.println(f.b);
}
}
结果如下:
Java 允许将多个静态初始化动作组织成一个特殊的“静态子句” (有时也叫做“静态块").
Java allows you to group other static initializations inside a special “static clause” (sometimes called a static block) in a class.
与其他静态初始化动作一样,这段代码仅执行一个:当首次生成这个类的一个对象时,或者首次访问属于那个类的静态数据成员时 (即便从未生成过那个类的对象).
Like other static initializations, is executed only once: the first time you make an object of that c lass or the first time you access a static member of that class (even if you never make an object of that class).
如果觉得不错,就用点赞或者关注来代替五星好评吧~
谢谢~