Instance Variable With Example In JAVA

An instance variable is a variable defined in a class (i.e. a member variable) in which each instantiated object of the class has a separate copy, or instance. An instance variable is similar to a class variable.

Instance variables belong to an instance of a class. It means instance variables belong to an object and we know that an object is an instance of a class. Every object has it’s own copy of the instance variables.


Instance Variable Declaration Example:

class Taxes
{
int count; //Count is an Instance variable
/*...*/
}

PROGRAM EXAMPLE WITH EXPLANATION:

Below is the program helps you to clearly understand the instance variables:

public class Record{

    public String name;// this instance variable is visible for any child class.

    private int age;// this instance age variable is visible in Record class only.

    public Record (String RecName)
    {
        name = RecName;
    }

    public void setAge(int RecSal)
    {
        age = RecSal;
    }

    public void printRec()
    {
        System.out.println("name : " + name ); // print the value for “name”
        System.out.println("age :" + age); //prints the value for “age”
    }

    public static void main(String args[])
    {
        Record r = new Record("Ram");
        r.setAge(23);
        r.printRec();
    }
}

Output:

name : Ram
age :23

In above example we take two instance variables one is name variable of string type and can be accessed by any child class because it is public and the second is age variable of integer type and can be accessed in the same class record because it is private.


Important Points About Instance Variable:

  • Instance variables are declared outside a method. It means they are declared in class.
  • When an object is created with the use of the keyword ‘new’ then instance variables are created and when the object is destroyed, instance variable is also destroyed.
  • In Java, Instance variables can be declared in class level before or after use.
  • For instance variables, access modifiers can be given.
  • The instance variables are visible for all methods(functions), constructors and block in the class.
  • Default values are given to instance variables. The default value is 0 for numbers, it is false for Boolean and it is null for object references.
  • Instance variables can be accessed directly by calling the variable name inside the class.