Java静态代码块(static block)调用陷阱小记
来源:互联网 发布:中国信贷数据 编辑:程序博客网 时间:2024/05/05 04:44
Java静态代码块(static block)调用陷阱小记
Java 中的static代码块并不一定会被调用。
设两个含静态方法和静态块的两个类(父类Base 子类Extend)
static块要写在public类里,所以两个类要写在单独的两个.java文件里
//父类
public class Base {
public static String who = "Mr. Base";
Base(){
}
static {
System. out.println("static block in Base" );
}
public static void functionInBase(){
System. out.println("static function in Base! -- " + who);
}
public void showWho(){
System. out.print(who);
}
}
view raw Base.java This Gist brought to you by GitHub.
//子类
public class Extend extends Base{
public static String who = "Mr. Extend";
static {
System. out.println("static block in Extend" );
}
public static void functionInExtend(){
System. out.println("static function in Extend!" );
}
Extend(){
super();
}
}
view raw Extend.java This Gist brought to you by GitHub.
//测试类
public class Main {
public static void main(String[] args) {
Extend.functionInBase();
Extend ex = new Extend();
ex.showWho();
System. out.println(Extend.who);
}
}
view raw Main.java This Gist brought to you by GitHub.
输出:
static block in Base
static function in Base! -- Mr. Base
static block in Extend
Mr. Base
Mr. Extend
陷阱1 www.2cto.com
可见在执行
Extend.functionInBase();
时类Extend中的静态代码块并未被执行,要让其执行的充分条件可以是(满足其中一项即可)
1. new 一个Extend类
2. 调用一个Extend类中实现的(而非继承下来的)静态方法
结论1:在一个未被初始化过的子类Extend中,调用Extend的父类实现的静态方法,Extend的静态代码块不会被调用。
陷阱2
在
Extend ex = new Extend();
后执行
ex.showWho();
时,并未如愿输出Mr. Extend 而是输出了:
Mr. Base
但是
System.out.println(Extend. who);
如愿输出
Mr. Extend
结论2:子类Extend从父类Base继承过来的静态方法调用的静态变量并不随着子类Extend中这个静态变量的覆盖而覆盖。
- Java静态代码块(static block)调用陷阱小记
- Java静态代码块(static block)调用陷阱小记
- Java静态代码块(static block)调用陷阱小记
- Java静态代码块(static block)调用陷阱小记
- Java静态代码块(static block…
- magento 静态块 static block 调用
- Magento调用静态块(static block) 实例
- 静态代码块(static block)
- java 静态语句块(static block)
- java static 与 static静态代码块
- Java day04 静态static,静态代码块
- magento中如何调用static block(静态块)
- 静态代码块static block-执行结果是什么?
- about "static block"(静态块)
- java静态代码块和静态方法的区别和调用顺序、static用法
- JAVA static{}静态代码块 和 {}
- 【Java总结】static,静态代码块
- Java基础--静态代码块:static{}
- 让linux find命令查询的结果为绝对路径
- JS:1.7窗口(window)对象 window.close,window.open
- Windows远程桌面连接ubuntu 14.04
- springMVC--ModelAndView Map对象详解
- 二---Android-NDK系列文章(1)
- Java静态代码块(static block)调用陷阱小记
- android开发工具网站
- pjsip视频
- Go语言smtp模块发纯文本文件
- activity 的启动模式 详细实验报告。。。
- JS:1.8字符串(string)对象(length,indexOf(),lastIndexOf(),replace(),match(),toUpperCase(),toLowerCase())
- operation on files named with hyphen '-'
- OpenGL之gluPerspective浅析
- 在oc中[]中括号的使用,去掉小数点后面的零,字符串的比较