Instance Variables
Instance variables are declared inside a class but outside a method, constructor, or block. Each instantiated object of a class has a separate copy of that variable. When you create a new object of a class you create an instance.
Let's look at this Vehicle Class. We have two instance variables vehicleName
and numWheels
.
1public class Vehicle {
2
3 private String vehicleName;
4
5 private int numWheels;
6}
If we were to create two Vehicle objects
1Vehicle car = new Vehicle();
2Vehicle van = new Vehicle();
Then each vehicle would have its own number of wheels and name. So the value stored inside vehicleName
and numWheels
would vary for different vehicles.
Static Variables
Static variables are also known as class variables because they are associated with the class. They are declared with the static keyword in a class but outside of a method, block or constructor. There would only be one copy of each static variable per class regardless of how many objects are created from it.
As you can see, the var
variable above was declared with the keyword static
and within class scope. The variable was accessed and modified by the exam
and exam2
variables. Notice that once the value of the var
variable was changed using exam2
, both objects accessing the var
variable now had the same value.
xxxxxxxxxx
class Example {
public static String
var = "This is your static variable";
}
public class Main {
public static void main(String[] args) {
Example exam = new Example();
Example exam2 = new Example();
//Both of these statements will display "This is your static variable"
System.out.println(exam.var);
System.out.println(exam2.var);
//Change the value of static variable usong exam2 object
exam2.var = " Changed static variable";
//Both of these statements will display "Changed static variable"
System.out.println(exam.var);
System.out.println(exam2.var);
}
}