1. Static domain
If the domain is defined as static, then there is only one such domain in each class. Each object has a copy of its own for all instance domains. For example, suppose you need to give each employee a unique representation code. This adds an instance domain ID and a static domain Nextld to the employee class:
Class Employee
{
private int id;
private static int nextid=1;
}
Now, each employee object has its own ID field, but all instances of this class share a NextID domain, in other words, if there are 1000 employee class objects, there are 1000 instance domain IDs, but only one static domain NextID, even if there is not an employee object, Static domain Nextil also exists, and he belongs to the class, not to any independent object.
Here's an easy way to do this:
public void SetId ()
{
Id= NextID;
nextid++;
}
Suppose Harry sets an employee identification code:
Harry.setid ();
Then Harry's ID field is set, and the value of the static domain NextID is added by 1:
Hurry.id= ...;
employee.nextid++;
2. Static constants
Static variables use less, but static constants use more, for example, a static constant is defined in the Math class:
public class Math
{
public static final double pi=3.14159265358979323846;
}
Access this constant through Math.PI in the program
If the keyword static is omitted, Pi becomes an instance field of the math class, which requires that the pi be accessed with the math class's pair, and each math object has his own copy of Pi.
Another static constant that has been used more than once is System.out, which he declares in the system class:
public class System
{
public static final PrintStream out= ...;
}
3. Static method:
A static method is a method that cannot be used to implement operations on an object. For example, the Pow method of the math class is a static method. The expression evaluates to a power that, when run, does not use any math object, in other words, without implicit arguments.
You can assume that a static method cannot manipulate an object, so you cannot access the instance domain in a static method. However, a static method can access a static domain in its own class. The following example:
public static int Getnextid ()
{
return NextID;
}
This method can be called by the class name:
int N=employee.getnextid ();
This method can omit static, but it needs to be called through a reference to the Employee class object.
201671010145 2016-2017 "Java programming" static domain and static method