Variables that are shared by every instance of a class are?

476    Asked by ArjunArora in Java , Asked on Oct 13, 2022

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?


Answered by Asutosh Jha
The answer to your question - Variables that are shared by every instances of a class are is -
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 its 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

Your Answer

Interviews

Parent Categories