Garikai
Garikai

Reputation: 425

Do multiple reference variables pointing to the same object each take up the same memory footprint as the object

Say for example I have four classes A, B, C and D; where D's constructor takes A, B and C as parameters. If I have the following implementation:

public static main(String[] args) {
  A = new A();
  B = new B();
  C = new C();
  D = new D(A, B, C);
}

And the instance variables for D are:

  private A objA;
  private B objB;
  private C objC;

Will, for instance, the "value" of A (new A()) be copied to objA after D's instantiation?

Upvotes: 0

Views: 770

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

Java only has references and primitive types. When you assign a reference to a variable it always takes the same amount if memory regardless of what object it references. Typically a reference is 4 bytes but can be 8 bytes for large heaps over 32 GB in size.

Will, for instance, the "value" of A (new A()) be copied to objA after D's instantiation?

In this case, the value of A is a reference to an object and that reference is copied. The object referenced isn't touched (neither copied or read)

Upvotes: 1

Related Questions