Instance variables store information unique to each object created from a class. They help keep data separate for each object.
0
0
Instance variables in Java
Introduction
When you want each object to have its own copy of data, like a person's name or age.
When you need to remember details about an object that can change independently from others.
When creating multiple objects that share the same structure but hold different information.
When you want to track the state of an object over time.
Syntax
Java
class ClassName { dataType variableName; // instance variable }
Instance variables are declared inside a class but outside any method.
Each object of the class has its own copy of instance variables.
Examples
Each Car object will have its own color and year.
Java
class Car { String color; // instance variable int year; }
Each Person object stores its own name and age.
Java
class Person { String name; int age; }
Sample Program
This program creates two Dog objects. Each dog has its own name and age stored in instance variables. The display method prints these details.
Java
class Dog { String name; // instance variable int age; void display() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } public class Main { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.name = "Buddy"; dog1.age = 3; Dog dog2 = new Dog(); dog2.name = "Max"; dog2.age = 5; dog1.display(); dog2.display(); } }
OutputSuccess
Important Notes
Instance variables get default values if not initialized (e.g., 0 for int, null for objects).
They belong to objects, so you access them through object references.
Use instance variables to keep data that varies from one object to another.
Summary
Instance variables hold data unique to each object.
They are declared inside a class but outside methods.
Each object has its own copy of instance variables.