17

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

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305

8 Answers8

20

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
13

Like with the maximum number of lambdas or the maximum of nested method invocations, we have to make a distinction between the formal Java language specification and technical limits, either due to the formally specified class file format or due to compiler limitations or bugs.

As often, the language specification does not define any limits on the number of constructors. So there’s only the practical limitation that the class declaration must be representable in the byte code format.

Constructors get compiled to special methods (named <init>), so in the class file, they share a table with ordinary methods, which is limited to 65535 entries. We can max this out by not declaring any ordinary methods. Further, since every constructor must have a distinct signature, each constructor needs its own type signature string in the constant pool, which is limited to 65534 entries on its own.

The constant pool also serves other purposes, like holding the declaration of this class, super class and the name of the Code attribute, which is needed when having constructors, as well as the linkage information of the super class’ constructor, we have to invoke, so this is the limiting factor on the class file side.

So the minimum constant pool entries needed, are

  1. super class name (modified UTF8 entry)
  2. super class (type Class, referring to 1.)
  3. this class name (modified UTF8 entry)
  4. this class (type Class, referring to 3.)
  5. the constructor’s “method” name <init> (modified UTF8 entry)
  6. a name&type entry referring to 5. and a super constructor signature (may be shared with one of our constructor’s signature)
  7. a method entry referring to 2. and 6. (for the super constructor invocation)
  8. the attribute name Code (modified UTF8 entry)

Given these required entries and the limit of 65534 entries (the size plus one is stored as unsigned two byte quantity), we get a class file limit of 65526 constructors and indeed, I could generate a valid class file using the ASM library with that number of constructors and not more.

Actually, you could get more if you name your class java.lang.Object, as in that special case, there is no super class to declare and no super constructor to invoke. Decide yourself, which actual limit you want to call the maximum number…

As said, there is a 3rd limitation, the compiler implementation. When using a Java compiler, you have to make sure that it doesn’t generate debug information (in case of javac, use -g:none) and no other optional attributes which could occupy constant pool entries. But with javac of JDK11, the performance will drop significantly when you start defining lots of constructors. I got the following compilation times:

 1000 constructors:   1 second
 2000 constructors:   2 seconds
 5000 constructors:  10 seconds
10000 constructors:   1 minute
15000 constructors:   2 minutes
20000 constructors:   4 minutes
30000 constructors:  10 minutes
40000 constructors:  20 minutes
50000 constructors:  between 25 minutes and ½ hour
65526 constructors:  between 45 minutes and 1 hour

So javac eventually managed to max out the class file limit, but we may consider a practical limit even before that.

The Eclipse compiler seems to deal better with such source files, but still, maxing out the number of constructors made the IDE almost unusable. With debug symbols turned off and a bit of patience, I managed to compile a class with 65526 constructors with Eclipse. Declaring 65528 constructors pro­duced an error message regarding too many constant pool entries and declaring 65527 constructors revealed a bug in Eclipse, producing a corrupt class file declaring zero constant pool entries (as said earlier, the number is stored as count plus one, so compiler vendors have to keep in mind that the limit is not 65535 but 65534).

Holger
  • 285,553
  • 42
  • 434
  • 765
  • 4
    If anyone wonders who would construct classes like that.. [here is the UI implementation of the Telegram App](https://github.com/DrKLO/Telegram/blob/e9e40cb13ea942b148b259c083fb3364a0cd90ea/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java) – Murat Karagöz Dec 12 '18 at 15:36
2

Java Support Constructor Overloading(When java class contain multiple constructors, it is called as constructor is overloaded).A class can have multiple constructors, as long as their signature(parameter) are not the same.So you can define many constructors as you need.There is no limit. Here is a Example:-

class Demo {
    private String name;
    private String city;
    private Double salary;

    public Demo() {
    }

    public Demo(String name) {
        this.name = name;
    }
    public Demo(Double salary) {
        this.city = city;
    }
    public Demo(String name,String city) {
        this.name = name;
        this.city = city;
    }
}
Jamith NImantha
  • 1,999
  • 2
  • 20
  • 27
2

You can have 65535 constructors in a class(According to Oracle docs). But IMPORTANTLY keep this in your mind. We achieve this only by CONSTRUCTOR OVERLOADING ( https://beginnersbook.com/2013/05/constructor-overloading/ ). You can create many constructors but with different signatures.

Tim
  • 41,901
  • 18
  • 127
  • 145
KR93
  • 1,098
  • 11
  • 10
1

tl;dr

For a class with reasonable functionality you will first run into other problems, both technical and non-technical. Technical limits imposed by the constant pool of the class file format for a useless class are:

  • 65526 for a class with a name of your choosing.
  • 65527 for a class named Code (one per class loader).
  • 65530 for a class named java.lang.Object (one per VM).

The details

The question was closed before I had posted my answer. So here's bits additional to that which @Holger has already covered.

The relevant section of the JVM spec is 4.1. The ClassFile Structure in the Java SE 11 edition.

u2             constant_pool_count;
cp_info        constant_pool[constant_pool_count-1];

Note the -1. The entries are numbered from 1. 0 is used to indicate:

  • a class with no superclass (interesting!)
  • a formal parameter with no name
  • a module with no version information
  • a module dependence with no version information

If the class is called Code then this string constant will be deduped with the required Code attribute name (see @Holger's answer). You will need a very old version of javac if you want to access it from outside of the default package.

It may be possible to remove a couple of the entries, if writing in byte code is not cheating, by throwing null (not a constant in bytecode) instead of calling super() or similar. I can't remember the exact details of bytecode verification for constructors - they certain cannot terminate normally without calling a this() or a super().

javac running increasingly slowly (O(n^2)ish?) is a good example of graceful degradation. :)

Playtime

You can see this for yourself quite easily by compiling small classes with varying numbers of constructors.

public class Min1 {
   public Min1() {
   }
   /* Followed by (int a), (byte a), (int a, byte b), etc. */
}

Compile without debug info (do people still accidentally distribute class files with debug info?).

javac -g:none Min1.java

List contents with good old javap.

javap -verbose Min1

Should give you something like

Classfile /Users/tackline/code/scratch/minimal_class/Min1.class
  Last modified Dec 5, 2018; size 119 bytes
  MD5 checksum c1a6b7c31c286165e01cc4ff240e7718
public class Min1
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #3.#7          // java/lang/Object."<init>":()V
   #2 = Class              #8             // Min1
   #3 = Class              #9             // java/lang/Object
   #4 = Utf8               <init>
   #5 = Utf8               ()V
   #6 = Utf8               Code
   #7 = NameAndType        #4:#5          // "<init>":()V
   #8 = Utf8               Min1
   #9 = Utf8               java/lang/Object
{
  public Min1();
    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
}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
0

You can have as many constructors in a class as you wish.. JAVA doesn't impose any restrictions on the number of constructors a class can have.. Just that constructors can be either parameterized or default..

default constructor: Default constructor does not have a parameters and is used to initialize every object with same data.

parametrized constructor: Parameterized constructor is having one or more parameters and is used to initialized each object with different data.

Harshith Rai
  • 3,018
  • 7
  • 22
  • 35
-1

You can create 65535 constructors in one class

More information: Oracle Docs

MidoZZX
  • 27
  • 7
-2

There's no limit on the number of constructors a class can have.

Mureinik
  • 297,002
  • 52
  • 306
  • 350