virpara virpara - 4 months ago 8
Java Question

What is difference between references and objects in java?

i have class GUI so i can create object like this

GUI g1 = new GUI();

and a reference variable like this

GUI g2;

now as much i know g2 is reference variable which gives reference to GUI class and g1 is object of GUI class. What is difference between g1 and g2? i can use property of GUI class with object but what is possible use of g2?


References are names. Objects are stuff. You can have different names for stuff, even for stuff that doesn't actually exist.

You can declare names, without actually giving them any "real" meaning, like this:

GUI g1;

You can assign meaning (real stuff to refer to) to names with the = operator:

GUI g1 = some_gui;

Names can change their meaning over time. The same name can refer to different things at different points in history.

GUI g1 = some_gui;


g1 = some_other_gui;

There are also synonyms: multiple names can refer to the same thing:

GUI g2 = g1;

That's pretty much what references do. They are names meant to refer to stuff.

Stuff can be created:

new GUI();

Stuff can be created and named on the spot for later reference (literally!):

GUI g1 = new GUI();

And stuff can be referred to, using its name (or any of its names!):


Different stuff of the same kind (Class) can be created, and named differently:

GUI g1 = new GUI();
GUI g2 = new GUI();
GUI g3 = new GUI();

GUI g1_synonym = g1;