Can a class have no constructor?
It is not required to explicitly define a constructor; however, all classes must have a constructor, and a default empty constructor will be generated if you don't provide any:
public Maze() {
}
See Default Constructor.
If you don't write the constructor explicitly, compiler will generate a no-args constructor by default.
public Maze(){
}
the above will be included If you don't write the constructor explicitly, compiler will generate a no-args constructor by default.
public Maze(){
}
the above will be included by the compiler.
for Example check the Byte code for this class:
public class ABC {
}
BYTE CODE:
public class sorting/ABC {
// compiled from: ABC.java
// access flags 0x1
public <init>()V //Default no-args constructor included by the compiler
L0
LINENUMBER 7 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init>()V
RETURN
L1
LOCALVARIABLE this Lsorting/ABC; L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1
}
To be more accurate, the compiler automatically provides a no-args constructor for a class that doesn't have a constructor, this constructor calls the no-args constructor of the superclass, if the superclass doesn't have a no-args constructor, it's an error, if it does, that's fine.
If your class has no explicit superclass, then it has an implicit superclass (Object
), which does have a no-args constructor.