Java Reference
In-Depth Information
When you run this application, the output should be the following:
Starting location:
X equals 4
Y equals 13
Moving to (7, 6)
Ending location:
X equals 7
Y equals 6
In this example, you first create an instance of Point where x equals 4 , and y equals 13
(line 6). Lines 9 and 10 display these individual values using dot notation. Lines 13 and
14 change the values of x to 7 and y to 6 , respectively. Finally, lines 17 and 18 display
the values of x and y again to show how they have changed.
3
Class Variables
Class variables, as you have learned, are variables defined and stored in the class itself.
Their values apply to the class and all its instances.
With instance variables, each new instance of the class gets a new copy of the instance
variables that the class defines. Each instance then can change the values of those
instance variables without affecting any other instances. With class variables, only one
copy of that variable exists. Changing the value of that variable changes it for all
instances of that class.
You define class variables by including the static keyword before the variable itself.
For example, consider the following partial class definition:
class FamilyMember {
static String surname = “Mendoza”;
String name;
int age;
}
Each instance of the class FamilyMember has its own values for name and age . The class
variable surname , however, has only one value for all family members: “Mendoza” .
Change the value of surname , and all instances of FamilyMember are affected.
Calling these static variables refers to one of the meanings of the
word static : fixed in one place. If a class has a static variable,
every object of that class has the same value for that variable.
NOTE
Search WWH ::




Custom Search