Junior
What are instance variables?
sobes.tech AI
Answer from AI
Instance variables are variables belonging to a specific instance (object) of a class. Each object has its own copy of these variables.
- Defined inside the class but outside of methods.
- Accessible from any method of the same class.
- Their value is unique for each instance of the object.
- Initialized when the class instance is created (for example, in the constructor).
Example in Java:
public class Dog {
String name; // instance variable
public Dog(String name) {
this.name = name;
}
public void printName() {
System.out.println("My name is " + this.name);
}
}
// Creating instances
Dog dog1 = new Dog("Buddy");
Dog dog2 = new Dog("Lucy");
// Each instance has its own 'name'
dog1.printName(); // Output: My name is Buddy
dog2.printName(); // Output: My name is Lucy
Comparison table:
| Variable | Belongs to | Scope | Lifecycle | Initialization |
|---|---|---|---|---|
| Instance variable | Each object instance | Inside the instance | As long as the instance exists | When the instance is created (constructor) |
| Static (class) variable | Belongs to the class itself (shared by all) | Everywhere in the class (often public) | Until the program ends | When the class is loaded |
| Local variable | Specific method or code block | Inside the method/block where declared | Only during the execution of the method/block | Must be initialized before use |