Java 习题 (43)

题目:
编写一个类,拥有两个静态字符串域,其中一个在定义处初始化,另一个在静态块中初始化。现在,加入一个静态方法用以打印出两个字段值。请证明它们都会在被使用之前完成初始化动作。

解答:

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).


如果觉得不错,就用点赞或者关注来代替五星好评吧~
谢谢~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值