Static Fields and Methods

时间:2021-12-28 13:39:28

If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example:

class Employee
{
private static int nextID = 1; private int id;
...
} public void setId()
{
id = nextId;
nextId++;
}

Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression Math.pow(x,a) computes the power. It does not user any Math object to carry out its task. In other words, **it has no implicit parameter*. You can think of static methods as methods that don't have a this parameter.

A static method of the Employee class cannot access the id instance field because it does not operate on an object. However, a static method can access a static field. For example:

public static int getNextId()
{
return nextId; //returns static field
}

To call this method, you supply the name of the class:

int n = Employee.getNextid();

You would need to have an object reference of type Employee to invoke the method if you omit the keyword static.