Class Variable Vs Instance Variable in Java with example

In the following class employee, empno, name, address are Instance Variable. Because they are local to the class , when number of objects are created of the same class , seperate copies of those variables are created. They are stored in different meory location.
Sno is the Class variable or static fields . Variable that have static modifier is called static fields or Class variable. They are associated with the class, rather than with any object. One memory location is shared for all the instance of the class and one time is initialised.



The output of the following code is
4
5
6
Whenever an employee object is created , sno is incremented by one. So employee id incremented

public class Emp{

public static void main (String arg[])
{
int k=0;
employee e=new employee(10,"emp1", "New delhi");

k=e.getID();
System.out.println(k);

employee e1=new employee(10,"emp2", "New delhi");
k=e1.getID();
System.out.println(k);

employee e2=new employee(10,"emp3", "New delhi");

k=e2.getID();
System.out.println(k);
}
}


class employee{

private int empno;
private String name;
private String address;
private int id;
private static int sno = 3;

public employee(int eno, String ename, String eadd){

empno = eno;
name = ename;
address = eadd;

// increments sno and assigns to id
id = ++sno;
}

// new method to return the id instance variable
public int getID() {
return id;
}

}

0 comments:

Post a Comment

 
Copyright 2011 Java Online