Example of a instance variable

This example will show how you can use a non-static variable.

Example of a instance variable

This example will show how you can use a non-static variable.

Example of a instance variable

Example of a instance variable

     

When a number of objects are created from the same class,  the same copy of  instance variable is provided to all. Remember, each time you call the instance the same old value is provided to you, not the updated one . In this program we are showing that how a instance variable is called in each instance, but the copy remains same irrespective the counter we have used in the constructor of a class. We can't call the non-static variable in a main method. If we try to call the non-static method in the main method then the compiler will prompt you that non-static variable cannot be referenced from a static context. We can call the non-static variable by the instance of the class.

The example will show you how you can use a non-static variables. First create a class named NonStaticVariable. Declare one global variable and call it in the constructor overloaded method in which you will have to increment the value of the variable by the counter. To access a  non-static variable we will have to make a object of NonStaticVariable by using new operator. Now call the instance variable. Now again make a new object of the class and again call the instance variable. Now you can realize that the value of the instance variable in both the object is same. 

Code of this program is given below:

public class NonStaticVariable{
  int noOfInstances;
  NonStaticVariable(){
  noOfInstances++;
  }
  public static void main(String[] args){
  NonStaticVariable st1 = new NonStaticVariable();
  System.out.println("No. of instances  for st1  : " 
  + st1.noOfInstances
);

  NonStaticVariable st2 = new NonStaticVariable();
  System.out.println("No. of instances  for st1  : " 
 
+ st1.noOfInstances);
  System.out.println("No. of instances  for st2  : " 
 
+ st2.noOfInstances);

  NonStaticVariable st3 = new NonStaticVariable();
  System.out.println("No. of instances  for st1  : " 
 
+ st1.noOfInstances);
  System.out.println("No. of instances  for st2  : " 
   + st2.noOfInstances
);
  System.out.println("No. of instances  for st3  : " 
 
+ st3.noOfInstances);

  }
}

The output of this variable is given below :

As we can see in the output the same copy of the instance variable is provided to all the objects, no matter how many objects we create.

C:\java>java NonStaticVariable
No. of instances for st1 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st1 : 1
No. of instances for st2 : 1
No. of instances for st3 : 1

Download this program