22

I'm very new to Java and want to understand the difference between class variables and instance variables.

For example:

class Bicycle { 
    static int cadence = 0; 
    int speed = 0; 
    int gear = 1; 
}

How are instance variables and class variables different from each other? Which variables here are class variables, and which are instance variables? How does this affect scope?

1

4 Answers 4

40

They both are member variables, meaning that both are associated with a class. Now of course, there are differences between the two:

Instance variables:

These variables belong to the instance of a class, thus an object. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class.

public class Product {
    public int Barcode;
}

Class variables:

These are also known as static member variables and there's only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.

public class Product {
    public static int Barcode;
}

Full example:

// INSTANCE VARIABLE
public class Main {

    public static void main(String[] args) {
    
        Product prod1 = new Product();
        prod1.Barcode = 123456;

        Product prod2 = new Product();
        prod2.Barcode = 987654;

        System.out.println(prod1.Barcode);
        System.out.println(prod2.Barcode);
    }
}

public class Product {
    public int Barcode;
}

The output will be:

123456

987654

Now, change the instance variable to a class variable by making it static:

//CLASS VARIABLE
public class Main {

    public static void main(String[] args) {
    
        Product prod1 = new Product();
        prod1.setBarcode(123456);
        Product prod2 = new Product();
        prod2.setBarcode(987654);

        System.out.println(prod1.getBarcode());
        System.out.println(prod2.getBarcode());
    }
}

public class Product {

    public static int Barcode;

    public int getBarcode() {
        return Barcode;
    }

    public void setBarcode(int value){
        Barcode = value;
    }
}

I used non-static methods to get and set the value of Barcode to be able to call it from the object and not from the class. The output will be following:

987654

987654

5
  • Why a C# example for a Java question? Commented Aug 12, 2015 at 7:42
  • My thoughts exactly.I only know java programming not C# , so you havent been of much help Commented Aug 12, 2015 at 7:51
  • 1
    @BasileStarynkevitch I'm mainly a C# developer and since the principle counts for both and is as good as the same I quickly provided a C# example, wrong of me of course. :) Changed my example to Java.
    – Abbas
    Commented Aug 12, 2015 at 8:13
  • 2
    @SkylarAdams Sorry, I wrongly assumed too quickly that anyone who knows Java, knows C#. I changed the example to a Java one, hope it helps.
    – Abbas
    Commented Aug 12, 2015 at 8:14
  • 9
    For this kind of question, I think it is irrelevant, whether using Java or C#, Commented Aug 12, 2015 at 13:13
6

It is explained here (with an example Bicycle class with class variable numberOfBicycles and instance variables cadence, speed, gear & id):

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

A class variable (declared static) is a location common to all instances.

In the example, numberOfBicycles is a class variable (since it is declared static). There is only one such variable (i.e. location) common to all instances and to the class. So if you modify numberOfBicycles in one method, other methods would see the new value (even for different Bicycle objects)

In contrast gear & id are instance variables (because their declaration has no static modifier). Every Bicycle object has its own one. If you modify gear for some Bicycle a, and if b is another instance, modifying a.gear has no effect on b.gear

Each Java object is a distinct memory zone with some meta data (e.g. some reference to its class) and its own instance variables (perhaps inherited from a superclass). But the class variables are common to the class and shared by all instances.

See also Object (computer science) & Instance variable wikipages.

0
4

Instance Variable:

  • Instance variables are declared in a class, but outside a method, constructor or any block.
  • Instance variable belongs to the instance of a class or you can say that instance variable belongs to the object.
  • Instance variable have separate value of each and every instance of the class.

    Class InstanceDemo {
    
         // this instance variable is visible for any child class.
           public String name = "Testing";
    
         // count variable is visible in Demo class only.
           private int count = 2;
    }
    

Method to access instance variable:

InstanceDemo demo = new InstanceDemo ();

System.out.println("Access Instance variable: " + demo.count + " , "+demo.name );

Output: 2 , Testing

Class Variable:

  • Class variable belongs to the class.
  • class variable is created by adding “static” keyword before the variable.
  • Also called static variable.
  • And most important class variable maintain a single shared value for all instance of a class, even if no instance object of the class exists.

        Class ClassDemo {
    
         // count variable is Same for all instance of this class
           public static int count = 2;
    }
    

Method to access class variable:

System.out.println("Access Class variable: " + ClassDemo.count );
//class variable is directly refer with class name

Output: 2

Brief Difference Between Class Variable and Instance Variable:

  • Instance variables have separate values for each instance of a class. Class variables maintain a single shared value for all instances of the class, even if no instance object of that class exists.
  • You would use the static keyword to change an instance variable into a class variable.
  • Both instance and class variables are declared at the class level, not within methods.
4

The difference between class variables and instance variables, is simply a question of who knows what?.

An instance variable is only known (= bound) to that concrete instance - hence the name.

  public class Person {
       private String firstName;
       private String lastName;
  [...]
  }

The definition of a class is like a blueprint for building concrete objects. Perhaps this point confuses you a bit. But writing it this way, every variable would be bound to its concrete object: e.g. Every person has its own firstName

A class variable on the other hand is - as the name says - known to each and every member of a class; or technically: It is known/ bound at class level. The typical example is a counter of how many objects, you have created - although it is a very problematic example; but that doesn't matter at this early stage.

  public class Person {
       private String firstName;
       private String lastName;
  [...]
       static int numberOfPersons = 0
  }

numberOfPersons is declared static which is the keyword to distingush between class variables and instance variabes. The variable is declared like the others within the class definition. But the static keyword signals, that it is different.

  • firstName, lastName are instance variables and bound to that concrete instance

  • numberOfPersons is bound to the class, so that every instance could access this variable.

tl;dr

The place where variables are defined is the class definition.

Class variables are known at/bound to the class level, i.e. each concrete instance has access to it. To define a class variable, you use the keyword static.

Instance variables are only known at an instance level. You define them without the static keyword.

Further documentation for Java is here

Not the answer you're looking for? Browse other questions tagged or ask your own question.