Exactly what are the differences between variables, objects, and references?
For example: they all point to some type, and they must all hold values (unless of course you have the temporary null-able type), but precisely how are their functions and implementations different from each other?
Example:
Dog myDog = new Dog(); //variable myDog that holds a reference to object Dog
int x = 12; //variable x that hold a value of 12
They have the same concepts, but how are they different?
(Just to be clear, the explanation I'm giving here is specific to Java and C#. Don't assume it applies to other languages, although bits of it may.)
I like to use an analogy of telling someone where I live. I might write my address on a piece of paper:
Does that help?
The difference between a value type and a reference type is what gets written on the piece of paper. For example, here:
int x = 12;
is like having a piece of paper with the number 12 written on it directly. Whereas:
Dog myDog = new Dog();
doesn't write the Dog object contents itself on the piece of paper - it creates a new Dog
, and then writes a reference to the dog on that paper.
In non-analogy terms:
Button
variable, the value will always be a reference to an object of type Button
or some subclass - or the null
reference.).
operator. For example, if foo
is a Person
variable, foo.getAddress().getLength()
would take the value of foo
(a reference) and call getAddress()
on the object that that reference refers to. The result might be a String
reference... we then call getLength()
on the object that that reference refers to.See more on this question at Stackoverflow