0

I am coming to Java from C++ and am having trouble grasping the true distinction between an object and a reference to the object.

When an object is instantiated a region of memory is reserved and to access/operate upon the data in the memory we use the reference to the object. This i understand but in my textbook the author states,

"An object reference variable that appears to hold an object actually contains a reference to that object. Strictly speaking, an object reference variable and an object are different, but most of the time the distinction can be ignored."

So I am curious as to when this distinction cannot be ignored. It kind of sounds like the way Pointers are distinguished from the address they point to. Do all Java reference variables operate in a similar fashion as C/C++ pointer variables? I.E are reference variables simply a pointer or reference to a memory address?

I have already gone through What are classes, references and objects? and I am still unclear as to how the distinction actually matters when working in Java. If anyone could provide an explanation or a link to a thorough explanation It would be greatly appreciated.

d0rf47
  • 409
  • 8
  • 20
  • 1
    In Java? You **never** have an actual object, you ***always*** have a reference to said object. All Java reference variables operate like C++ reference variables. Yes, all reference variables are internally a reference to some memory address within the JVM. – Elliott Frisch Jan 25 '20 at 18:14
  • Yeah thats what I thought but the quote from the text was confusing me. – d0rf47 Jan 25 '20 at 18:15
  • Cause later the author states " Usually you create an object and assign it to a variable, then later you can use the variable to reference the object. Occasionally, an object does not need to be referenced later. In this case, you can create an object without explicitly assigning it to a variable" I don't understand why – d0rf47 Jan 25 '20 at 18:18
  • In java when you write Object o you created variable that has reference to Object. That means that Object o in Java is in C++ Object *o. Edit: What author want to say in this quote in comment is that you can do "new Object()" without assigning it to variable like "Object o=new Object();" – Милош Којадиновић Jan 25 '20 at 18:29
  • Yeah but is there any practical reason for doing that? – d0rf47 Jan 25 '20 at 18:38
  • Fluent interfaces. Method "dot" chaining. `String s = new StringBuilder().append("Hello, ").append("World!").toString();` or `new Something().thatDoesSomething();` – Elliott Frisch Jan 25 '20 at 18:41
  • Okay that makes sense i guess. Appreciate the input. – d0rf47 Jan 25 '20 at 18:43

0 Answers0