2) Java Classes - A Blueprint For Objects Lesson

What is an Instance Variable in Java?

3 min to complete · By Ryan Desmond

In Java, an instance variable is a variable that is bound to the instance of a class rather than being associated with a particular method or block of code. Each instance of the class has its own copy of the instance variables. These variables represent the state of an object and define its properties.

Instance variables are declared within a class but outside of any method, constructor, or block. They are usually initialized in the class itself or within the constructors of the class.

What do Instance Variables Do in Java?

Each instance of a class (each object) gets its own instance variables. Instance variables are also visible to other members within the same class and other classes, depending on access modifiers.

What are Access Modifiers?

Access modifiers are keywords that are used in the declaration of a variable, method, and class to determine what other elements in the program can see and use them. Two examples of access modifiers are public and private, but you'll read about this more in the next section.

table showing various access modifiers in Java and their permissions

Java Instance Variable Example

The following class has two instance variablesname and age. When an object of this class is created, each object gets its own set of variables.

class Person{

    // "name" is an instance variable of type String
    String name;

    // "age" is an instance variable of type int
    int age;

} 

This means that you could create a Person whose name is John and has an age of 27 but also create another Person with a different name and a different age; this is all thanks to instances and object-oriented programming!

Summary: What is an Instance Variable in Java?

  • Instance variables are variables declared outside of methods
  • Instance variables are members of a class
  • Instance variables are visible to other members within the same class
  • Instance variables can also be visible to other classes, depending on their access modifiers