I’ve been programming Java for 2 years now, and I have encountered a problem where I couldn’t understand and differentiate class, reference, and an object.
I am not sure if a class or reference are the same, though I have an idea of what an object is.
Can someone differentiate in a complete manner what classes, references, and objects are?
All I know is that a class is more like a template for an object (blueprint to a house where the class is the blueprint and the house is an object).
If you like housing metaphors:
You can copy that reference as much as you like, but there’s just one house — you’re just copying the card that has the address on it, not the house itself.
In Java, you can not access objects directly, you can only use references. Java does not copy or assign objects to each other. But you can copy and assign references to variables so they refer to the same object. Java methods are always pass-by-value, but the value could be an object’s reference. So, if I have:
Then let’s see what’s happening.
new Foo()tells the JVM to build a new house using theFooblueprint. The JVM does so, and returns a reference to the house. You then copy this reference tomyFoo. This is basically like asking a contractor to build you a house. He does, then tells you the house’s address; you write this address down.callBar. Let’s jump to that method next.Foo foo. Java is pass-by-value, so thefooincallBaris a copy of themyFooreference. Think of it like givingcallBarits very own card with the house’s address on it. What doescallBardo with this card? It asks for a new house to be built, and then uses the card you gave it to write that new house’s address. Note thatcallBarnow can’t get to the first house (the one we built in line 1), but that house is unchanged by the fact that a card that used to have its address on it, now has some other house’s address on it.myFooto call a method on it (doSomething()). This is like looking at the card, going to the house whose address is on the card, and then doing something in that house. Note that our card withmyFoo‘s address is unchanged by thecallBarmethod — remember, we gavecallBara copy of our reference.The whole sequence would be something like:
myFoo.callBar. Before we do, we copy the address written onmyfooto a new card, which we give tocallBar. It calls that cardfoo.callBarasks the JVM for another house. It creates it, and returns the new house’s address.callBarcopies this address to the card we gave it.