سؤال

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() {
    }
}
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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

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?

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top