In Java, how many constructors can we create within a single class.
There are two types of constructors parameterized constructors and no-arg constructors.
There can be only one special method with the name constructor in a class. Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.
Within a class, you can create only one static constructor. A constructor doesn't have any return type, not even void.
In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading.
Strictly speaking, the JVM classfile format limits the number of methods (including all constructors) for a class to less than 65536. And according to Tom Hawtin, the effective limit is 65527. Each method signature occupies a slot in the constant pool. Since some of the 65535 pool entries are (unavoidably) consumed by other things, it is not possible for a well-formed class file to use all of the possible method / constructor ids.
Reference - JVMS 4.1 The ClassFile Structure
However, if you are writing sensible Java code the normal way, you won't encounter that limit.
How many should you have? It depends on the classes use-cases. It is often nice to have multiple "convenience" constructor overloads, and implement them using this(...)
to chain to a "master" constructor. (However, you can go over the top. There are N! possible combinations (overloads) of N distinct parameters.)
If you find that you are writing an excessive (subjective!) number of constructors, you should maybe look at alternatives such as the Builder Pattern.
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