Static variable:
Static variables are declared using the keyword static.
Every instances of the particular class shares the same static variable , that means if the changes are made to the static variable, then all the instances of that class will get affected.
In the following example ‘color’ is a static variable within the class Ball.
We created a constructor of this class to pass the color variable.
Then created two instances within the main method with different values of color- red and blue
Then we called the getcolor() method for each instance, but the output came as below –
The color of the ball is blue
The color of the ball is blue
As the static variable’s value changes from red to blue so , it affected all the instances of the class.
public class Main {
public static void main(String[] args) {
Ball b=new Ball(“red”); //instance with color=red
Ball c=new Ball(“blue”); //instance with color=blue ; the variable’s value changes from red to blue
b.getcolor(); //The color of the ball is blue
c.getcolor(); //The color of the ball is blue
}
}
class Ball{
private static String color;
public Ball(String color) {
Ball.color=color;
}
public void getcolor() {
System.out.println(“The color of the ball is “+color);
}
}
Instance Variable:
For instance variable don’t use the keyword static.
Instance variables affect the specific instance of the class.
Every instance has it’s own copy of specific instance variable.
public class Main {
public static void main(String[] args) {
Ball b=new Ball(“red”); //instance with color=red
Ball c=new Ball(“blue”); //instance with color=blue ; the variable’s value changes from red to blue.
b.getcolor(); //The color of the ball is red
c.getcolor(); //The color of the ball is blue
}
}
class Ball{
private String color;
public Ball(String color) {
this.color=color;
}
public void getcolor() {
System.out.println(“The color of the ball is “+color);
}
}