Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 961
Abhinay Vijay Phuke Avatar asked Dec 05 '18 05:12

Abhinay Vijay Phuke


People also ask

How many constructor are there in Java?

There are two types of constructors parameterized constructors and no-arg constructors.

How many constructor functions can you include in a class definition?

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.

How many constructors can be created for a class justify?

Within a class, you can create only one static constructor. A constructor doesn't have any return type, not even void.

Can we execute more than one constructor at a time?

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.


1 Answers

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.

like image 130
Stephen C Avatar answered Oct 26 '22 08:10

Stephen C