// Foo foo = new Foo();对应的字节码 // new指令:请求内存 0: new // class me/zhongmingmao/basic/jol/Foo 3: dup // invokespecial指令:调用构造器 4: invokespecial // Method "<init>":()V
如果一个类 没有定义任何构造器 ,那么Java编译器会自 动添加一个无参数的构造器
// 未定义任何构造器 public class Foo { public static void main(String[] args) { Foo foo = new Foo(); } }
// Foo类的构造器会调用父类Object的构造器 public me.zhongmingmao.basic.jol.Foo(); descriptor: ()V flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 // [this] 1: invokespecial // Method java/lang/Object."<init>":()V 4: return
public class A { } class B extends A { }
$ javap -v -p -c B me.zhongmingmao.basic.jol.B(); descriptor: ()V flags: Code: stack=1, locals=1, args_size=1 0: aload_0 // [this] 1: invokespecial // Method me/zhongmingmao/basic/jol/A."<init>":()V 4: return $ javap -v -p -c A public me.zhongmingmao.basic.jol.A(); descriptor: ()V flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 // [this] 1: invokespecial // Method java/lang/Object."<init>":()V 4: return
public class C { public C(String name) { } } class D extends C { public D() { // 直接显式调用 super("Hello"); } public D(String name) { // 间接显式调用 this(); } }
$ javap -v -p -c D public me.zhongmingmao.basic.jol.D(); descriptor: ()V flags: ACC_PUBLIC Code: stack=2, locals=1, args_size=1 0: aload_0 1: ldc // String Hello // 直接显式调用 3: invokespecial // Method me/zhongmingmao/basic/jol/C."<init>":(Ljava/lang/String;)V 6: return public me.zhongmingmao.basic.jol.D(java.lang.String); descriptor: (Ljava/lang/String;)V flags: ACC_PUBLIC Code: stack=1, locals=2, args_size=2 0: aload_0 // 间接显式调用 1: invokespecial // Method "<init>":()V 4: return
$ javap -v -p -c C public me.zhongmingmao.basic.jol.C(java.lang.String); descriptor: (Ljava/lang/String;)V flags: ACC_PUBLIC Code: stack=1, locals=2, args_size=2 0: aload_0 1: invokespecial // Method java/lang/Object."<init>":()V 4: return