Core Java Volume I-4.4. Static Fields and Methods

Source: Internet
Author: User
Tags pow

4.4. Static Fields and Methods
in all sample programs, the seen, the main method was tagged with the static modifier. We is now ready to discuss the meaning of this modifier.
4.4.1. Static Fields
If You define a field as static and then there are only one such field per class. In contrast, each object have its own copy of the all instance fields. For example, let's suppose we want to assign a unique identification number to each employee. We Add an instance field ID and a static field NextID to the Employee class:
class Employee
{
private static int nextid = 1;
private int id;
. . .
}
every employee object now have its own ID field, but there are only one NextID field that's shared among all instances of the class. Let's put it another. If there is objects of the Employee class, then there is the instance fields ID, one for each object. But there was a single static field NextID. Even if there is no employee objects, the static field NextID is present. It belongs to the class and not to any individual object.
Note
in some object-oriented programming languages, static fields is called Class
Fields . The term "static" was a meaningless holdover from C + +.
Let's implement a simple method:
Public void SetId ()
{
id = nextid;
nextid++;
}
Suppose you set the employee identification number for Harry:
Harry.setid ();
Then , the ID field of Harry was set to the current value of the static field NextID, and
The value of the static field is incremented:
harry.id = Employee.nextid;
employee.nextid++;
4.4.2. Static Constants
Static variables is quite rare. However, static constants is more common. For example, the Math class defines a static constant:
Public class Math
{
. . .
Public static final double PI = 3.14159265358979323846;
. . .
}
You can access the constant in your programs as Math.PI.
If The keyword static had been omitted, then PI would has been an instance field of the Math class. That's, you would need a object of this class to access PI, and every Math object would has its own copy of Pi.
another static constant that's used many times is System.out. It is declared in the System class as follows:
Public class System
{
. . .
Public static final printstream out = ...;
. . .
}
as we mentioned several times, it's never a good idea to the public fields, because everyone can modify them. However, public constants (that's, final fields) is fine.
Since out have been declared as final, you cannot reassign another print stream to it:
System.out = new PrintStream (...);//Error--out is final
Note
If you are in the System class, you'll notice a method setOut that sets System.out to a different stream. Can wonder how that method could change the value of a final variable. However, the SetOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround it should not emulate in your programs.
4.4.3. Static Methods
The Static methods is methods that does not the 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 xa. It does not use any of the Math object to carry out its task. In the other words, it has no implicit parameter.
You can think of the static methods as methods that don ' t has a this parameter. (In a nonstatic method, the This parameter refers to the implicit parameter of the Method-see section 4.3.5, "Implicit and Explicit Parameters, "on p.)
Since static methods don ' t operate on objects, you cannot access instance fields from a static method. However, static methods can access the static fields in their class. Here's an example of such a static method:
public static int Getnextid ()
{
return nextid;//returns static field
}
to call this method, you supply the name of the class:
int n = employee.getnextid ();
Could you have omitted the keyword static for this method? Yes, but so you would need to has an object reference of type Employee to invoke the method.
Note
It is the legal to use a static method of object to call a. For example, if Harry was an Employee object and then you can call Harry.getnextid () instead of Employee.getnextid (). However, we find that notation confusing. The Getnextid method doesn ' t look at Harry at all to compute the result. We recommend that the use class names, not objects, to invoke static methods.
Use the static methods in the situations:
When a method doesn ' t need to access the object state because all needed parameters is supplied as explicit parameter S (EXAMPLE:MATH.POW).
When a method is only needs to access the static fields of the class (Example:Employee.getNextId).
C + + Note
The Static fields and methods has the same functionality in Java and C + +. However, the syntax is slightly different. In C + +, you use the:: operator to access a static field or method outside its scope, such as Math::P I. The term "static" had a curious history. At first, the keyword static were introduced in C to denote local variables that don ' t go away when a block is exited. In this context, the term "static" makes sense:the variable stays around and was still there when the block is entered Aga In. Then the static got a second meaning in C, to denote global variables and functions that cannot is accessed from the other files. The keyword static is simply reused, to avoid
introducing a new keyword. Finally, C + + reused the keyword for a third, unrelated, interpretation-to denote variables and functions that belong to a Class but not to any particular object of the class. that's the same meaning the keyword have in Java.
4.4.4. Factory Methods
Here are another common use for static methods. The NumberFormat class uses factory methods that yield formatter objects for various styles.
NumberFormat currencyformatter = Numberformat.getcurrencyinstance ();
NumberFormat percentformatter = Numberformat.getpercentinstance ();
Double x = 0.1;
System.out.println (Currencyformatter.format (x));//Prints $0.10
System.out.println (Percentformatter.format (x));//Prints 10%
Why doesn ' t the NumberFormat class use a constructor instead? There is reasons:
You can ' t give names to constructors. The constructor name is always the same as the class name. But we want, different names to get the currency instance and the percent instance.
When you use a constructor, you can ' t vary the type of the constructed object. But the factory methods actually return objects of the class DecimalFormat, a subclass that inherits from NumberFormat. (see Chapter 5 for more on inheritance.)
4.4.5. The main Method
Note that the can call static methods without have any objects. For example, you never construct any objects of the Math class to call Math.pow.
for the same reason, the main method is a static method.
Public class Application
{
Public static void Main (string[] args)
{
//Construct objects here
. . .
}
}
The Main method does not operate on any objects. In fact, when a program starts, there aren ' t any objects yet. The static Main method executes, and constructs the objects, the program needs.
Tip
every class can has a main method. That's a handy trick for unit-testing of classes. For example, you can add a main method to the Employee class:
class Employee
{
Public Employee (String N, double s, int., int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar (year, month-1, day);
hireday = Calendar.gettime ();
}
. . .
Public static void Main (string[] args)//unit test
{
Employee E = new Employee ("Romeo", 50000, 2003, 3, +);
E.raisesalary (ten);
System.out.println (E.getname () + "" + e.getsalary ());
}
. . .
}
If you want to test the Employee class in isolation, simply execute
Java Employee
IF the Employee class is a part of a larger application and then your start the application with
Java Application
And the main method of the Employee class is never executed.
The program in Listing 4.3 contains a simple version of the Employee class with a static field NextID and a static met Hod Getnextid. We fill an array with three employee objects and then print the employee information. Finally, we print the next available identification number, to demonstrate the static method.
Note that the Employee class also have a static main method for unit testing. Try running both
Java Employee
and
Java statictest
To execute both main methods.

Core Java Volume I-4.4. Static Fields and Methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.