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

5

5

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() {
    }
}
Billbug answered 2/4, 2013 at 14:59 Comment(0)
B
9

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.

Breana answered 2/4, 2013 at 15:1 Comment(0)
A
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.

Aiken answered 2/4, 2013 at 15:0 Comment(0)
W
2

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

Whiteman answered 2/4, 2013 at 15:1 Comment(0)
A
1

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?

Arango answered 6/4, 2015 at 10:33 Comment(0)
P
0

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.

Polygynist answered 2/4, 2013 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.