What are instance variables in Java?

15 May

Instance variables are any variables, without “static” field modifier, that are defined within the class body and outside any class’s methods body.

Instance variables are in scope as long as their enclosing object is in scope. An instance variable is a part of the object that contains it and cannot live independently of it.

All object instances have their own copies of instance variables. One object instance can change values of its instance variables without affecting all other instances.

Instance variables can be used by all methods of a class unless the methods are marked with “static” modifier. You access instance variables directly from their containing object instances.

A class or object can have it’s own variables. In Java, these are called instance variables. By its definition, an instance variable is unique to each instance of the class; so in general, each time a class is “instantiated” with the new operator, there is another variable associated with it.

These variables are declared outside any methods you may have. These variables are declared either public, private or protected. They are global to the class or object they appear in. Let’s see a small example.

Example:

public class Variables{

   private int x = 0;

   public Variables(){
      x++;
      System.out.println("Welcome! " + x);
   }
   public static void main(String args[]){
      Variables var1 = new Variables();
   }
}

In this example, the instance variable x is declared private. In addition, it is global to the Variables object.

The program simply prints out “Welcome! 1” when the program starts.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: