Explain the difference between instance variable and a class variable?
An instance variable is a variable which has one copy per object/instance.That means every object will have one copy of it.
A class variable is a variable which has one copy per class.The class variables will not have a copy in the object.
String empName, department;
static int officePhone;
An object referred by empObj1 is created by using the following:
Emp empObj1=new Emp();
The objects are referred by instance variables empObj1 and empObj2 have seperate copies empNo,empName, department and salary.However the officePhone belongs to the class(class variable) and can be accessed as Emp.officePhone.
Class variables can be accessed using either class name or object reference. Instance variables can be accessed only through object reference.
Class variables are common to all instances of a class. These variables are shared between the objects of a class. Instance variables are not shared between the objects of a class.