5.8 Static Methods and Variables


5.8 Static Methods and Variables

If a method does not belong to an object, but it is defined in a class, the method is normally called with the class name, a dot, and then the method name. No object needs to be referenced when calling such a method. For example:

       set y = Math.sin(x) + 109.5 

In this case, sin is a static method of the Java class Math. To define a static method, the keyword static is written before the name of the method. For example:

       function static mymethod is       . . .       endfun mymethod 

Static variables are not associated with any object. These variables should normally be private and should be accessed and/or updated using accessor and mutator functions. To declare a static variable in a class, the keyword static is written before the normal variable declaration. For example, the following statement declares a static variable named num_var and initializes it to zero value.

       static integer num_var = 0 

For every declaration of a static variable, there is only one copy of its value shared by all objects of the class.

A static method cannot reference nonstatic variables and cannot include calls to nonstatic methods. The basic reason for this is that nonstatic variables and methods belong to an object, static variables and methods do not.

Often, static variables are also known as class variables, and static methods as class methods.




Object-Oriented Programming(c) From Problem Solving to Java
Object-Oriented Programming (From Problem Solving to JAVA) (Charles River Media Programming)
ISBN: 1584502878
EAN: 2147483647
Year: 2005
Pages: 184

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net