What I really want to know is: say I would create a class called "Family" in Java, and each family would have a number of "familyMembers" as member variables, would it cost any more memory to also declare for each of the "familyMembers" what "Family" they are part of? in other words, say the family Smith has 3 members, Dad, Mom and Kid, would it cost any more memory to make Family "Smith" a member variable of each familyMember: Dad, Mom and Kid?
-
2This isn't very clear; can you provide some code snippets to illustrate what you're talking about? – Oliver Charlesworth Mar 30 '14 at 16:36
-
Providing code snaps will better explain the probkem – Abimaran Kugathasan Mar 30 '14 at 16:37
-
1Yes, any new (non static) object reference in a class costs additional 4 bytes. – luke1985 Mar 30 '14 at 16:37
-
1@lukasz1985 That is platform dependent. 64-bit implements of Java often (but not always) use 64 bits (8 bytes) for object references. Here's a reference: http://stackoverflow.com/questions/5520731/how-to-test-how-many-bytes-an-object-reference-use-in-java – Erwin Bolwidt Mar 30 '14 at 16:44
3 Answers
unless you use the new
keyword or primitive type, you only use memory needed to store the reference

- 2,260
- 2
- 19
- 26
-
1
-
okay so every reference costs a bit of memory? Does that mean that adding more family members, and therefore more references to the "Smith" Family, would cost more memory? – Ushwald Mar 30 '14 at 16:49
-
1@Ushwald: Every sandwich costs 5 dollars. Does that mean that buying more sandwiches would cost more money? – JB Nizet Mar 30 '14 at 16:51
-
yes, but I'm not talking about declaring more variables here, I'm talking about referring to the same variable in more than one way – Ushwald Mar 30 '14 at 16:54
-
2You don't refer to a variable. You refer to an object. Each time you have a reference to an object, the reference needs to store the address of the object. And that costs 4 bytes of memory. – JB Nizet Mar 30 '14 at 17:00
Everything costs something. If adding another class variable, it will cost in two ways. First some bytes for your declaration in the class when it is loaded and then for each reference another 4 bytes. This is because you class definition must be loaded into memory (permanent, permgen space) and because every reference is unique on your stack the 4 bytes per reference.

- 2,018
- 25
- 32
Yes, the reference to the family, when stored in a family member, increases the instance size of a family member by the size of a reference.
Note that in practice this does not necessarily mean more memory consumption because of various memory management techniques Java VMs use.

- 4,345
- 2
- 23
- 35