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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With