import
java.util.
*
;
public
class
Demo
{ static { System.out.println( " i am static demo. " ); } { System.out.println( " i am demo. " ); } static void print() { System.out.println( " can omit instance initialization? " ); } public static void main(String[] args) { new Sub( " child " ); Demo.print(); } }
abstract
class
Base
{ public String name = " " ; public String sex = " base " ; public Base(String name) { System.out.println( " name: " + this .name); this .name = name; System.out.println( " invoke base constructor " ); System.out.println( " name: " + name); this .setName( " parent " ); } { System.out.println( " invoke base instance block " ); System.out.println( " this.sex: " + this .sex); printInfo(); } static { System.out.println( " invoke base static block " ); } // public abstract void setName(); public abstract void printInfo(); public void setName(String name) { this .name = name; System.out.println( " invoke parent setName method " ); System.out.println( " name: " + name); } }
class
Sub
extends
Base
{ public static int age = 10 ; public String sex = " sub " ; public Sub(String name) { super (name); System.out.println( " invoke sub constructor " ); System.out.println( " name: " + name); } { System.out.println( " invoke sub instance block " ); System.out.println( " name: " + name); } static { System.out.println( " invoke sub static block " ); } public void printInfo() { System.out.println( " " ); System.out.println( " invoke sub printInfo " ); System.out.println( " age: " + age); System.out.println( " name: " + name); System.out.println( " " ); } public void setName(String name) { System.out.println( " invoke sub setName method " ); this .name = name; System.out.println( " name: " + name); } }
输出结果;
i am static demo. invoke base static block invoke sub static block invoke base instance block this.sex:base
invoke sub printInfo age:10 name:
name: invoke base constructor name:child invoke sub setName method name:parent invoke sub instance block name:parent invoke sub constructor name:child can omit instance initialization? 初始化的实际过程为:
- 在其它任何事物发生之前,将分配给对象的存储空间初始化成二进制的零。
- 父类static 块或变量
- 子类static块或变量
- 父类的显式初始化
- 父类构造函数
- 子类的显式初始化
- 子类的构造函数