Java Reference
In-Depth Information
You can use the class name or a reference variable of the class type to refer to a class variable. since the class
variable belongs to the class and it is shared by all instances of the class, it is logical to refer to it using the class name.
however, you always use a reference variable of a class type to refer to the instance variables.
Tip
It is time to see the use of fields in the Human class. Listing 6-2 has a complete program that demonstrates how to
access class variables and instance variables of a class.
Listing 6-2. A Test Class to Demonstrate How to Access (Read/Write) Class Variables and Instance Variables
of a Class
// FieldAccessTest.java
package com.jdojo.cls;
class FieldAccessTest {
public static void main(String[] args) {
// Create an instance of Human class
Human jack = new Human();
// Increase count by one
Human.count++;
// Assign values to name and gender
jack.name = "Jack Parker";
jack.gender = "Male";
// Read and print the values of name, gender and count
String jackName = jack.name;
String jackGender = jack.gender;
long population = Human.count;
System.out.println("Name: " + jackName);
System.out.println("Gender: " + jackGender);
System.out.println("Population: " + population);
// Change the name
jack.name = "Jackie Parker";
// Read and print the changed name
String changedName = jack.name;
System.out.println("Changed Name: " + changedName);
}
}
Name: Jack Parker
Gender: Male
Population: 1
Changed Name: Jackie Parker
 
Search WWH ::




Custom Search