4

Consider:

public SomeClass implements SomeInterface{...}

SomeClass obj = new SomeClass();

SomeInterface x = obj;

I am trying to relate line 3 to my very basic understanding of memory management. I know the memory location represented by "obj" just contains a pointer to the memory location of SomeClass. Assuming I am using a 64bit JVM, then up to 64 bits are allocated for the "obj" pointer. What is created in memory when the JRE implements x? Is it just a 64bit pointer to SomeClass?

jlordo
  • 37,490
  • 6
  • 58
  • 83
James Rogers
  • 69
  • 1
  • 7

3 Answers3

3

Every object reference takes up the same amount of memory, no matter how you declare it.

So x and obj are two distict references, which just happen to point at the same thing.

barfuin
  • 16,865
  • 10
  • 85
  • 132
  • 1
    *Every object reference takes up the same amount of memory*. Is this strictly true under CompressedOops? https://wikis.oracle.com/display/HotSpotInternals/CompressedOops – NPE Dec 07 '12 at 14:56
  • @NPE Well, if you go down deep enough, many easy truths don't hold. Like, objects in the real world don't really have color etc. But I think for the sake of the question, my statement is true. – barfuin Dec 07 '12 at 14:59
  • What then is the purpose of declaring x as type SomeInterface? Why not just say SomeClass x = obj; Are the two statements doing the exact same thing? – James Rogers Dec 07 '12 at 15:15
  • @James Rogers Generally, you want to declare objects using their interface type, because then you could swap the implementation class to some other class without changing the code (e.g. a `HashSet` and a `TreeSet`are both `Set`s). That's a different question though. – barfuin Dec 07 '12 at 15:17
  • @Thomas, if I understand you correctly you are saying the advantage of an interface is that I can do this? SomeOtherClass implements SomeInterface{...} SomeOtherClass someOtherObj = new SomeOtherClass(); x = someOtherObj; – James Rogers Dec 07 '12 at 15:26
1

In simple sentence references take same memory in Java however declared.

Stack and Heap for Memory Allocation this will help you understand in detail how it

enter image description here works.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
0

There's no actual memory overhead, the SomeInterface declaration is at this point simply a language construct, typing x for later checking by the compiler.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • Are you saying that `x` occupies zero amount of storage, including no storage for the reference itself? – NPE Dec 07 '12 at 14:57
  • No, there is storage for the variable, but it's not different from any other reference. The fact that it's an interface doesn't change that. – Will Hartung Dec 07 '12 at 17:02