-1

In java if I have class called Coder and I write like -

Coder coder1 = new Coder();

then coder1 is called reference variable, right? As it is referencing Coder class, but why then any Object created using new keyword is called Object of that type/class rather than reference variable of that class. Or are both things synonymous. Please clear my doubt!!

zaidKnight
  • 5
  • 1
  • 3

2 Answers2

2

An object is the thing that holds the values. You create it using new Coder(). It has no name.

A reference variable is a thing that points to that object. You can think of it as a name that you give it.

If you just create new Coder() and never let anything point to it it will be pointless and eventually garbage collected, because there's no way to reference it.

If you do

Coder coder1 = new Coder();

then coder1 is a reference to the object. You can use it to call methods on the object like coder1.toString().

You can even create another reference that points to the same object:

Coder coder2 = coder1;

It might look like you now have 2 Coder objects, but you don't. There's still only one. You have 2 references to it (or "names" if you will). coder1.toString() will do the exact same thing as coder2.toString(), because they reference the same object.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • Ok! got it coder1 is a reference to an Object of class/type Coder which has been created using the new keyword. I was of an opinion that coder1 is also an object which its not. Thank You. – zaidKnight Jul 11 '18 at 12:14
  • Note that colloquially people might say things like "the `Coder` object `coder1`", which is **technically** not correct, but universally understood to mean "the `Coder` object that *`coder1` points to*". – Joachim Sauer Jul 11 '18 at 12:16
  • yeah! that's the thing that confuses some like me to think of reference variables as objects! thank you for that comment of yours, cleared my doubt. – zaidKnight Jul 11 '18 at 12:19
0

You have the Class (Coder), from which you can create objects. When you use new, you create an object which type is Coder, then this object is allocated a memory space, than new return and store the reference to this object in coder1.

mkharraz
  • 61
  • 1
  • 8