Java Reference
In-Depth Information
Notice you can access a static field using a reference to an instance
of that particular class. For example, you can access the counter and
getCounter() fields using any Employee reference, as demonstrated by
the method call:
e.getCounter()
in the StaticDemo program. Although it is valid, I would discourage using
a reference instead of the preferred syntax of using the class name. Using
a class name makes it clear that the field or method is static.
Static Methods Cannot Access
Instance Members
What happens if an instance field or method is accessed from within a static method? For
example, the getCounter() method in the following Employee class attempts to set the
name field to “Rich.”
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 static int getCounter()
{
System.out.println(“Inside getCounter”);
name = “Rich”; //does not compile!
return counter;
}
}
I want to make a couple of important observations about the getCounter() method's
setting name to “Rich.” The getCounter() method is static, so the method does not belong
to any particular instance of Employee. In fact, we can invoke getCounter() with zero
Employee objects in memory. If there are no Employee objects in memory, there are no
name fields in memory; therefore, in this case, it does not make sense to set name equal
to “Rich” because there are no name fields anywhere.
Search WWH ::




Custom Search