Java Instance Variables

In this post, you will learn to:

  • State the purpose of instance variables.
  • State the syntax of declaring instance variables.

Concept of Instance Variables

Instance variables are used to store information about an entity.

Consider a scenario, wherein a car dealer wants to keep track of the price of various cars in stock. So, to store the prices of various cars, you need variables. Accordingly, you need several local variables to store prices. However, an alternative is to create a class and declare a variable named price in it. This enables every instance created from this class to have its own copy of the price variable referred as the instance variable.

Note: The benefit of using instance variables over local variables is that you declare only one instance variable and use it for all instances of the class. The name of the instance variable is shared across all instances, but each instance has its own copy of the instance variable.

Declare and Access Instance Variables

Instance variables are declared in the same way as local variables. The declaration comprises the data type and a variable name. An instance variable also has an access specifier associated with it. Instance variables are declared inside a class but outside any method definitions. They can be accessed only through an instance using the dot notation.

The following is the syntax for declaring an instance variable within a class.

Syntax:

[access_modifier] data_type instanceVariableName;

where,
access_modifier is an optional keyword specifying the access level of an instance variable. It could be private, protected, and public.
data_type specifies the data type of the variable.
instanceVariableName specifies the name of the variable.

The following code demonstrates the declaration of instance variables within a class in Java program.

Code Snippet:

1: class Book {
2: int price;
3: …
4:
5:    public static void main(String[] args) {
6:       Book objJava = new Book();
7:       obj.price = 34;
8:    }
9:    …
10:   }

In the code, line 2 declares an instance variable named price of type int. Line 7 accesses the instance variable price and assigns it the value 34. Note, that to access an instance variable, you first create an instance. Next, you qualifying the instance variable name with an instance name followed by a dot.

Related Post