As you might have already noticed, the name of the blog is ‘Object Oriented‘. Bearing that in mind, why not start off with a lightweight & simple topic – Objects
Sounds too primitive? Talking about Objects? Really? It’s 2014 ! But please bear with me.
This quick fire post might prove to be helpful for the ones who are probably setting out on the ‘Java’ journey. So, let’s dive in . . .
A simple question . . . What are Objects in Java?
Well, the simple answer to that – ‘objects’ are ‘instances‘ of classes which in turn are ‘blueprints‘ or ‘templates’ for the objects themselves.
How are objects declared or instantiated?
The general way of declaring an object is by using the new keyword which invokes the constructor of a class e.g.
User user = new User();
How does one work with this declared object?
The declared objects are referred to by variables – not just simple variables. They are known as object reference variables. e.g. In the above example, user is an object reference variable
What’s the significance of this object reference variable? Does it store the inherent value of the object?
This is where beginners often lose the plot.
- The object reference variable is nothing but a pointer (Please do not confuse this with pointers in C++). Think of this pointer as a handle to the object it refers to.
- Remember this: The object reference variable itself does not store the value of the object it is referring to
- The variable is stored in an area of the memory known as the Stack and what it points to is the address of the location where the object which it is referring to is stored. This location is another part of the memory known as the Heap.
- Thus, the object reference variable represents the Heap Address of the object which it is referring to.
To help en grain the concept of object reference variables, imagine a dog with a leash, where the dog is the object and the leash is the object reference variable
Dog With A Leash: A properly instantiated object
Dog dog = new Dog(“Tuffy”)
Dog Without A Leash: An object which has not been stored in a variable yet
A Leash Without A Dog: An object reference variable which has not been initialized or referred to an object (it’s value is null)
Dog sadDog = null;
A Dog With Many Leashes: Many reference variables, pointing towards the same object
Dog aDog = new Dog(“dogOne”);
Dog anotherDog = aDog;
This was supposed to be a ‘quick’ one…. there you go!
Thanks for reading!