What is difference between references and objects in java?
A reference is an entity which provides a way to access object of its type. An object is an entity which provides a way to access the members of it's class or type.
Generally, You can't access an object without a reference to it.
class GUI
{
void aMethod()
{
// some business logic.
}
}
You can call aMethod
with or without a reference. but you definitely need an object.
Without Reference:
new GUI().aMethod();
// you can't reuse the object
// bad way to code.
With Reference:
GUI aGUIReference = new GUI();
aGUIReference.aMethod();
// Now, the object can be reused.
// Preferred way to code
Now a little explanation to your code lines:
GUI g1 = new GUI();
// g1 is a reference to an object of GUI class.
GUI g2;
// g2 is a reference that can point to an object of GUI class
// but currently not pointing to any.
The only difference b/w g1
and g2
is that g1
is initialized with an object but g2
points to null
g2 = g1;
// it means g2 will point to the same object g1 is pointing to
// only one object but two references.