What gets called when you initialize a class without a constructor? [duplicate]

淺唱寂寞╮ 提交于 2019-12-07 06:10:42

问题


So when a class has a private constructor you can't initialize it, but when it doesn't have a constructor you can. So what is called when you initialize a class without a constructor?

As example, what is called here (new b())??

public class a {
    public static void main(String args[]) {
        b classB = new b();
    }
}

public class b {
    public void aMethod() {
    }
}

回答1:


There's no such thing as a "class without a constructor" in Java - if there's no explicit constructor in the source code the compiler automatically adds a default one to the class file:

public ClassName() {
  super();
}

This in turn can fail to compile if the superclass doesn't have a public or protected no-argument constructor itself.




回答2:


It's called the default constructor. It's automatically added when a class doesn't explicitly define any constructors.

Formal specification:

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
If the class being declared is the primordial class Object, then the default constructor has an empty body.
Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.




回答3:


the default no argument constructor is invoked - see here for more information




回答4:


When in doubt, use javap.

Empty.java:

public class Empty {
    public static void main(String[] args) {}
}

Then:

javac Empty.java
javap -v Empty.class

Output excerpt:

public Empty();
  descriptor: ()V
  flags: ACC_PUBLIC
  Code:
    stack=1, locals=1, args_size=1
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

Ha! A constructor got generated. If we try the same for:

public class Empty {
    public Empty() {}
    public static void main(String[] args) {}
}

we see exactly the same bytecode.

I have asked if this is a Java-only restriction or if it is also present on the bytecode-level at: Is it valid to have a JVM bytecode class without any constructor?




回答5:


There is an invisible default constructor that looks something like this:

public B() {
   super();
}

When you call new B(), this implicit constructor gets called.

One note, in Java we use the convention that class names begin with an uppercase alphabetic character. So I have changed that for you.



来源:https://stackoverflow.com/questions/15767449/what-gets-called-when-you-initialize-a-class-without-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!