Instance Variables
Submitted by jeffheaton on Thu, 01/10/2008 - 03:54
Instance variables are declared outside of a function or method. Instance variables can be accessed anywhere in the class in which they were declared. A new set of instance variables is created for each class instance created. Consider the following example in Listing 6.3.
Listing 6.3: Using an Instance Variable (MyClassInstance.java)
class MyClassInstance
{
public int x = 0;
public static void main(String args[])
{
MyClassInstance myclass1 = new MyClassInstance();
MyClassInstance myclass2 = new MyClassInstance();
myclass1.x = 10;
myclass2.x = 15;
System.out.println(
"Current value of myclass1.x is ",myclass1.x);
}
}This program will print out 10. There are two instances of MyClass created, named myclass1 and myclass2. Each of these two instances have their own copy of the instance variables, and as a result each have their own unique x variable. If x were to have been declared static, they would have been the same variable. A static x would have caused 15 to be printed out.












