Java Variables Examples 1 – Instance Variables

Instance Variables Flow Chart
What is an instance variable? A class member that each instance of the class inherits, each containing an independent value from the same member in other instances.

Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

Referencing Java Certification Tutorial, Section 1-1 Variables

In the following sample code, we set up a class. This class will be referenced in our application. This class has two instance variable members, speed and gear. While each bike shares a variables named speed and gear each instance has its own variable, with its own place in memory and value.

In a simple example, we’ll set up the Bicycle instances with a speed using setSpeed and then print out the speed using getSpeed.

This bikeName> speed is an example of an instance variable.  “scwinn” and “trek” are the instances of Bicycle for this simple example. Each bike is passed a speed and then it is printed by using the appropriate get method we put in the class.

schwinn and trek are each a instance of the class Bicycle, each one has a separate instance of the member speed . This is the same thing as saying it “has an instance variable named speed.”

A few more notes:

These variables are only accessible within the Bicycle class.  In order to change them or retrieve them, we have to invoke the class and then invoke the class’s method (getSpeed and setSpeed). We are not invoking them directly.

Inside the Bicycle class, we can use the name inside the class, unless it contains a more specifically identified variable with the same name. If we use it unambiguously and without a more specific variable (see: getSpeed) we can just use the identifier for the instance variable.

If we use the same name/identifier in the same method, than we have to use this.identifier. In this case the member can be access via “this.speed” (see: setSpeed).

You created a simple app that can assign and read the value of speed for a bike, which is an instance of a class. An instance variable is another name for the value held by a variable in an instance of a class. Each instance of the class Bicycle has its own variable identified by then name speed. Because it is an instance variable, speed for each Bicycle instance is a different variable, has its own place in memory, and can have independently assigned values.

Written By StevenLacks