In Java how many constructor can we create in one class?

Abhinay Vijay Phuke :

In Java, how many constructors can we create within a single class.

Stephen C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35719&siteId=1