Friday, 8 March 2013

Objects in Java


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.

Lets move on to how to create an object in Java.

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();

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

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.

Classes in Java

We said that one of the advantages of using Java as a programming language over C is its Object Oriented nature.In this tutorial lets see what it means to be an object oriented programming language. In this post we will see what are classes, what are objects and how they interact with each other.

What is OOP?

     OOP(Object oriented programming) means your program or code comprises of objects and these objects interact with each other to deliver the final result you are interested in.Why to program in an OOP language one might ask.Well, there are many advantages to use an OOP language over other languages. Some of them are Data Encapsulation, Polymorphism, Inheritance etc. These terms may sound a little advanced at this point of time but we will have separate posts of each of them.

    So lets get started with Classes and Objects.

Classes in Java

   Classes in java are nothing but blue print or templates for creating objects. Syntax for defining a class is

<AccessModifier> Classname
    member variable
    member functions

As  we had mentioned in post on Access modifier just recall that class level modifier are public and no modifier(default). So you can have only either public  as a access modifier or nothing  i.e just class. I would recommend just go through the access rules table Access Modifiers once again.
    Classname can be any name of your choice as long as it follows the naming rules.Take a quick look at the Naming Rules . Class definition must go inside curly braces following the class name. Inside these curly braces you must specify member variables Eg. private int count and member functions Eg. public int getCount() or public void setCount(int count).

Naming conventions for classes and its members

    There is a standard naming conventions that all Java programmers follow.These are not mandatory rules but some standards defined to make our lives easy.

Note  - A common convention for all is that try to give meaningful names relevant to your project or code.For example you are writing a program say to print "Hello World!", then you can have class name something like MyGreetings.
  • Package : If you don't know what a package is it is simply a directory or rather call it a structure which hols all your classes.It is recommended to make your our package and put your classes there than to use the default package.Package name must be entirely in lower case.
    Eg. package greeting or package com.javatutsforgeeks.greetings. For all your classes in a package must have first line as package packageName . If you are using an IDE like Eclipse or Netbeans you will automatically see it when you create a class inside a package. For others you have to manually specify.
  • Classes : Class names must be in Camel case.In Camel case all sub-words in a word start with an upper case.Also try giving name to your class which is a noun because a class represents an object in real world. Ex class MyGreeting .
  • Interfaces : Same convention as classes. Do not worry about interfaces for now.It's a very interesting topic and we will cover it soon after we learn inheritance. 
  • Members : Now when i say a member it can be a member variable or a member function. Conventions are same for both. Member name must start with a lowercase and starting letter of all subsequent sub-words are in capital letter.
    Eg. private String welcomeMessage or public String printGreetingd(String message).

Note : Your class name should be same as your file name in which you have your class. For example if your class is like public class MyGreeting then your file name should be Again an IDE will do this automatically for you but if you coding in some editor like notepad++ or vim then you must take care of this.

But i heard that we can have two classes in one file.What should we do in that case?

     Yes it is possible to have more than one class defined in a single file.In this case you must give file name same as the name of first class in your file.Though this is allowed it is strongly recommended to have one class per file.

Writing classes - Example

     Lets write complete code so that we understand classes completely once and for all.

package greetings;

public class MyGreetings {
    private String welcomeMessage;

    public String getWelcomeMessage() {
        return welcomeMessage;

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    public static void main(String args[])
        MyGreetings greetings = new MyGreetings();
        greetings.setWelcomeMessage("Welcome to javatutsforgeeks!");

 Explaination - Above code defines a class called MyGreetings in a package called greetings. It has a member variable called welcomeMessage which is of type String and has access modifier as private. We then have member function which are nothing but getter and setter methods for our member variable welcomeMessage. Then we have out main() function which creates an object of our class MyGreetings, sets the value for member variable and prints it to standard output.

Quick Note : Since our member variable welcomeMessage is defined to be private we cannot access it using greeting. welcomeMessage and hence we have our getter and setter methods. This also forms a base for data encapsulation which we will study later.

Member variables and member functions

Member variable have the syntax 
AccessModifier variableType variableName;
Eg. private int count;
Member functions have the syntax
AccessModifier returntype functionName(arguments);
Eg. public void setCount(int count); 
 As stated earlier we have four member level access modifiers.Go through the post on Member level Access modifiers to review it once again.

We already know the Access modifiers and return types.Lets focus on arguments now.Arguments are parameters or variables that you want to pass to a function.These are local variables and their scope extend in the particular function only.You can pass as many arguments as you want.
Eg. public void setCountandName(int count,String name);
In Java we pass arguments as pass-by-value which means a copy of the reference to the object is passed.

Note : Java is pass by value! Java passes objects as references and those references are passed by value.

 We will see what are objects, how we create them in next post.This is one of the basic posts that forms the basis of other posts yet to come..Please let me know if you have any question.I will be more than happy to clarify them.

t> UA-39527780-1 back to top