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?
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.
b) A class should contain an average of less than 30 methods, resulting in up to 900 lines of code.
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).
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.
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.
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