Background
In last post we learned what is a class, what does it represent and how do you define one.Lets move on to knowing about objects.Before proceeding to knowing objects in details it is important to know difference between instance variable and local variables.Difference between local variable and instance variable
- Instance variable are class level member variables where as local variable are variables defined locally in functions or code blocks.
- Values of instance variables are unique to each instance of a class i.e objects of that class.
- In programming languages such as Java, instance variables are stored on the stack memory allocated by the Operating system. This contrasts with reference variables (variables that are references to existing instance variables) which are stored on the heap.
- Instance variables are always assigned a default value.
Creating an object in java
Before i show you how we create any object in java let me explain a bit of it's technical part.So as we know Java is an OOP language which means everything is an object which also means everything must have an associated class.
This object which we keep referencing so ofter is parent class of all classes that exist in Java i.e classes which are already defined in Java libraries as well as Classes which you(User) defines. In more technical terminology all classes extends from object class. I know polymorphism and inheritance are not yet covered so i will not get into details of this but for now just keep in mind all classes inherit/extend or is a direct or indirect child of class object.
Lets go ahead in creating objects. You create object using the keyword new. Syntax for creating an object is as follows
ClassName objectName = new ClassName();
ClassName is the name of the class whose object you wish to create. objectName is the name of the object.It can be any user defined name as long as it sticks to naming rules.
Eg. MyGreeting greeting = new MyGreeting();
Consider following code
Now references 'c' and 'd' point to same Book instance on Heap where as reference 'c' point to a difference instance. So
I hope this completely clears the difference between a reverence variable and an actual object.
Eg. MyGreeting greeting = new MyGreeting();
Where are objects stores in Java?
Before i answer this question there is one thing you must understand which is difference between reference and an actual object.When i just say MyGreeting greeting; it is perfectly valid. What are we doing here is that we are saying greeting is a reference to an object which will be of type MyGreeting. Note that we have not created object yet.Object is created only when we use that new keyword. So when i say MyGreeting greeting = new MyGreeting(); there is a reference variable called greeting of type MyGreeting and there is an object created using new of MyGreeting class and the greeting reference points to that created object.
I hope now we understand what is a reference variable and what is an object.So lets get to our original question where are objects stored? Objects are always stores on the heap(also known as garbage collectable heap) where as reference variable are stored on stack. So to sum it up greeting variable is stored on stack and points to an object in the heap.Remember heap is where the memory needed for the object is allocated and this memory allocation is automatic.Also this memory is freed automatically by garbage collector which we will see in detail after some time.Note garbage collector is invoked automatically by JVM. We can also specify to invoke garbage collector by using System.gc() but still it is not necessary JVM will invoke garbage collector when it encounters above command.Do not worry about garbage collector for now.Our primary focus is to learn objects in this post.
Consider following code
Book b = new Book(); Book c = new Book(); Book d = c;
Now references 'c' and 'd' point to same Book instance on Heap where as reference 'c' point to a difference instance. So
System.out.println(c == d); //will print true System.out.println(c == b);//will print false
I hope this completely clears the difference between a reverence variable and an actual object.
What actually happens when i create an object?
When you create an object, more specifically when you use the new keyword an instance on the class is returned as an object.It will have its own copy of instance variables and functions.First thing that happens after an object is created is calling of a constructor.So lets understand constructors in our next post.
What are getter and setter methods we keep referring to?
As we define our member variable to be private which we should because that is the essence of data encapsulation(will be explained later), we cannot directly access these variables using object as objectName.variableName. So we must define public methods which will be use to get and set the values of such member variables.These methods are called getter and setter methods.Since the functions are public we can use our object to get or set value of any member function i.e value of any private member variable can only be changed by member variables in same class.If you are using an IDE like Eclipse or Netbeans you can directly generate these getter and setter methods.Go to Source-->Generate getters and setters.
I have seen usage like "this.VariableName" is a class.What is that?
This question can be better explained using an example. Consider an setter method for some member variable private int count;
public void setCount(int c) { count = c; }
Observer above code carefully.We have not used this.count and is still perfectly valid.Now we know that count is an instance variable and c is a local variable.In case c was named as count(why not it's perfectly valid) then the function would be something like below
public void setCount(int count) { count = count; }
Though this may look valid, this will give erroneous results. Now which count is which.It is for cases like this we use this.variableName to avoid confusion and maintain standards. this.variableName means that the variable is an instance variable.
So finally your function will look like
public void setCount(int count) { this.count = count; }
You will specifically see this when you are automatically generating setter methods using an IDE.You can always use different name for local variable but using this.variableName will help you as well as others understand the code better.
Finally what is the difference between a class and an object?
A class is a blue print for an object!
It tells JVM how to create object of that particular type.Each object made from that class have it's own values for the instance variables of the class. For eg cosider
Above Dog class represent a Dog. Each dog will have unique breed and height (have just taken two properties for argument sake .... we can consider more) that will determine what type of Dog it is. So as I said previously Classes are blueprints of Objects.
It tells JVM how to create object of that particular type.Each object made from that class have it's own values for the instance variables of the class. For eg cosider
public class Dog { String breed; int height; }
Above Dog class represent a Dog. Each dog will have unique breed and height (have just taken two properties for argument sake .... we can consider more) that will determine what type of Dog it is. So as I said previously Classes are blueprints of Objects.