group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
263 Members
Join this group to post and comment.
AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
30 Jan 2019

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.

Example:

class Emo{

   int empNo;

   String empName, department;

    double salary;

     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.

Archana Priyadarshini
Archana Priyadarshini
Computer Science
2mos ago

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.