Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the maximum number of fields a Java class can have?

Tags:

java

jvm

Is there a limit to the number of fields a java class or an associated object instance can have, and if so what is it?

I am explicitly asking about fields, not methods as was asked in this question: What is the maximum number of methods a Java class can have?

like image 938
Andreas Hartmann Avatar asked Dec 28 '17 17:12

Andreas Hartmann


People also ask

How big can Java classes be?

class file contains a magic number (4 bytes), a version (4 bytes), the constant pool (variable size), etc. But sizes can be defined on several levels: you can have 65535 methods and each is limited to 65535 bytes.

What is the maximum number of methods that a Java class can contain?

b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.

What is the maximum number of methods a class can have?

The number of methods that may be declared by a class or interface is limited to 65535 by the size of the methods_count item of the ClassFile structure (§4.1).

How many classes can a Java program have?

One of the most frequent questions that come up in our mind. A single Java program can contain more than one class and there are no restrictions on the number of classes that can be present in one Java program.


1 Answers

The class file format contains a list of field declarations whose size is an unsigned short, hence could allow 65535 declarations, but it is not possible to declare 65535 fields in practice.

Each field must have a unique name and type combination and these names and types are stored in the constant pool of the class, which can only hold up to 65534 entries, but will also contain the constants describing the current class and its super class and the attribute names, among other features. Every feature of the class which needs dedicated constant entries will reduce the possible number of declared fields.

So for Java source code, which requires all fields to have unique names, it is impossible to declare that many fields in a class. With handcrafted byte code, you may utilize the fact that names do not need to be unique, to declare 65535 fields, but you cannot use all of them within the same class, as accessing the field requires a “name and type” entry describing the unique combination, plus a field descriptor pointing to the “name and type” entry and the declaring class.

But keep in mind that classes can inherit fields from the super class.

like image 85
Holger Avatar answered Oct 15 '22 10:10

Holger