Java Reference
In-Depth Information
Because System is a class, we can assume (correctly) that out is a static field in
the System class. The out field represents the standard output, and you do not
need to instantiate a System object to access this field.
Let's look at an example that demonstrates writing and accessing static
fields and methods. The following Employee class contains a static field, a
counter, and a static method, getCounter().
public class Employee
{
private String name;
private String address;
private int SSN;
private int number;
public static int counter;
public Employee(String name, String address, int SSN)
{
System.out.println(“Constructing an Employee”);
this.name = name;
this.address = address;
this.SSN = SSN;
this.number = ++counter;
}
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name
+ “, number “ + number);
}
public static int getCounter()
{
System.out.println(“Inside getCounter”);
return counter;
}
}
Notice that the Employee constructor accesses counter without using
the class name prefix, assigning it to the number field. The methods in a
class can access the static fields in the same class without using the class
name; therefore, in the Employee class, we can simply use counter instead
of Employee.counter.
The following StaticDemo program accesses the counter field and get-
Counter() method of Employee. Because these members are static, you use the
Employee class name when referring to them. For example, to access the
counter field, use:
Employee.counter
Search WWH ::




Custom Search