Mark As Completed Discussion

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.

TEXT/X-JAVA
1public class Vehicle {
2
3    private String vehicleName;
4
5    private int numWheels;
6}

If we were to create two Vehicle objects

TEXT/X-JAVA
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.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment