An instance variable is a type of variable in Java that is declared inside a class but outside any method, constructor, or block. These variables are associated with objects of the class and are stored in the heap memory when the object is created. Each instance of a class (object) has its own copy of the instance variables.
Characteristics of Instance Variables
- Declared Inside a Class: Outside of any method, constructor, or block.
- Belongs to an Object: Each object of the class has its own separate copy of the instance variable.
- Default Values: If not explicitly initialized, they are assigned default values:
- Numeric types (
int
,float
, etc.):0
- Boolean:
false
- Reference types:
null
- Numeric types (
- Access Modifiers: Can be declared with
private
,protected
,public
, or package-private (default) access modifiers. - Lifecycle: They exist as long as the object exists and are destroyed when the object is garbage collected.
- Access: Accessed through an object reference (e.g.,
objectName.variableName
).
Syntax
class ClassName {
// Instance variable
DataType variableName;
// Example with initialization
DataType variableName = value;
}
Example
class Car {
// Instance variables
String brand;
String color;
int speed;
// Constructor to initialize instance variables
public Car(String brand, String color, int speed) {
this.brand = brand; // `this` refers to the current object's instance variable
this.color = color;
this.speed = speed;
}
// Method to display car details
public void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Color: " + color);
System.out.println("Speed: " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
// Create objects (instances) of the Car class
Car car1 = new Car("Toyota", "Red", 180);
Car car2 = new Car("Honda", "Blue", 200);
// Access and modify instance variables
car1.displayDetails();
car2.displayDetails();
// Modify an instance variable for car1
car1.speed = 190;
System.out.println("Updated Speed for car1: " + car1.speed);
}
}
Output
Brand: Toyota
Color: Red
Speed: 180 km/h
Brand: Honda
Color: Blue
Speed: 200 km/h
Updated Speed for car1: 190
Key Points
- Separate Memory: Each object has its own copy of the instance variables, so changing one object’s variable doesn’t affect another object’s variable.
- Access with
this
Keyword: Thethis
keyword is used to refer to instance variables when there’s ambiguity with local variables or method parameters. - Scope: Instance variables can be accessed by all methods of the class unless restricted by access modifiers.