Java static variable

xiaoxiao2021-03-06  82

Java static variables are equivalent to class fields without being understood as object fields.

Static Fields and Methods

In All Sample Programs this.

Static FieldsIf 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, 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 intend; private static int nextId = 1;}

Now, every employee object has its own id field, but there is only one nextId field that is shared among all instances of the class. Let's put it another way. If there are one thousand objects of the Employee class, then there are one thousand instance fields id, one for each object. But there is a single static field nextId. Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object.

In Most Object-Oriented Programming Languages, Static Fields Are Called Class Fields. The Term "Static" IS 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 Is Set, And The Value of The Static Field NextId Is Increment:

Harry.id =...; Employee.Nextid ;

ConstantsStatic Variables Are Quite Rare. However, Static Constants Are More Common. For Example, The Math Class Defines a static constant:

Public class math {.. Public static final double pi = 3.14159265358979323846;.....................

If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every object would have its own copy of PI.

Another Static Constant That You Have Used Many Times IS System.out. It is deflared in the system class as:

Public Class System {...........

As we mentioned several times, it is never a good idea to have public fields because everyone can modify them. However, public constants (that is, final fields) are ok. Since out has been declared as final, you can not reassign another print stream To IT:

Out = new printstream (...); // error - Out is final

If you look at the System class, you will notice a method setOut that lets you set System.out to a different stream. You may wonder how that method can 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 that you should not emulate in your own programs.

Static MethodsStatic 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, y)

Computes The Power Xy. It Does NOT Use Any Math Object To Carry Out Its Task. in Other Words, IT Has No Implicit Parameter.

.

Because static methods do not operate on objects, you can not access instance fields from a static method But static methods can access the static fields in their class Here is 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 ();

.

It is legal to use an object to call a static method. For example, if harry is an Employee object, 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 You Use Class Names, Not Objects, To Invoke Static Methods.

You Use Static Methods in Two Situations:

WHEN a Method Doesn't Need To Access The Object State Because All Needed Parameters Are Supplied As Explicit Parameters (Example: Math.Pow);

WHEN a Method ONLY Needs to access static fields of the class

Static fields and methods have 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 :: PI.

. The term "static" has a curious history At first, the keyword static was introduced in C to denote local variables that do not go away when exiting a block In that context, the term "static" makes sense:. The variable stays around and is still there when the block is entered again. Then static got a second meaning in C, to denote global variables and functions that can not be accessed from other files. The keyword static was 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 is the same meaning that the keyword has in Java.Factory MethodsHere is another common use For Static Methods. Consider the Methods

Numberformat.getnumberinstance () Numberformat.getCurrencyInstance ()

That We discussed in chapter 3. Each of these methods returns an Object of type number, for example,

Numberformat formatter = Numberformat.getCurrencyInstance (); system.out.println (formatter.format (salary)); // Prints Salary with Currency Symbol

As you now Know, this area,.

Why do not we use a constructor instead? There are two reasons. You can not give names to constructors. The constructor name is always the same as the class name. In the NumberFormat example, it makes sense to have two separate names for getting number and currency formatter objects. Furthermore, the factory method can return an object of the type NumberFormat, or an object of a subclass that inherits from NumberFormat. (See Chapter 5 for more on inheritance.) A constructor does not have that flexibility. .................. ..

For The Same Reason, The Main Method Is A Static Method.

Public class application {public static void main (string [] args) {// construct Objects here..}

.................. ..

Every Class Can Have A Main Method. That Is 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 year, 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); E.raisSalary (10); System.out.Println (e. GetName () " E.Getsalary ());}..

If you want to test the Employee Class in ISOLATION, you Simply ExecuteJava Employee

If The Employee Class Is A Part of A Larger Application, Then You Start The Application with

Java Application

And the main method of the employee class is never exec executed.

The program in Example 4-3 contains a simple version of the Employee class with a static field nextId and a static method getNextId. We fill an array with three Employee objects and then print the employee information. Finally, we print the number of identification numbers Assigned.

Note That The Employee Class Also Has A Static Main Method for UNIT Testing. Try Running Both

Java EMPLOYEE

and

Java Statictest

TO EXECUTE Both Main MAIN.

Example 4-3 statictest.java 1. Public class statictest 2. {3. public static void main (string [] args) 4. {5. // Fill the stff Array with three Employee Objects 6. Employee [] staff = new Employee [3]; 7. 8. Staff [0] = New Employee ("Tom", 40000); 9. Staff [1] = New Employee ("Dick", 60000); 10. Staff [2] = New Employee ("Harry", 65000; 11.12. // Print Out Information About All Employee Objects13. FOR (INT i = 0; I

转载请注明原文地址:https://www.9cbs.com/read-96013.html

New Post(0)