Static Methods


Static Methods

The second general category of methods is static, or class, methods. A static method is associated with a class rather than with an individual object. A static method is designated as such by including the static keyword in the method declaration. Static methods are often used to implement generic functionality that can be used by a wide variety of classes. As such, static methods are often given public access.

A static method can be called inside the class in which it is defined simply by typing the method name followed by any input arguments. To call a static method outside of the class in which it is defined, you must type the class name, a period, the method name , and any input arguments.

 class_name.method_name(arguments); 

You can also call a static method through an object reference, but this is never necessary and is considered a bad practice.

Static methods can only access other static members . You must use an object to call an instance method from within a static method. Static methods can only act upon static variables. A static method will not have access to any instance variables since these are associated with an object rather than with the class itself. Static methods cannot reference the this or super keywords since these refer to objects as well.

Example: Defining Static Methods

Static methods are often used for implementing mathematical functions that can be used in a variety of applications. The StaticDemo class defines a static method named hypotenuse () that returns the hypotenuse of a right triangle. The method is given public access so it can be called directly outside of the StaticDemo class. Note that the hypotenuse() method itself calls a static method, sqrt() from the Math class.

 public class StaticDemo {   public static double hypotenuse(double height,                                   double width) {     return Math.sqrt( height*height + width*width );   } } 

To access the hypotenuse method outside of the StaticDemo class, you must type StaticDemo.hypotenuse along with the method arguments. The CallStatic class demonstrates how this can be done.

 public class CallStatic {   public static void main(String args[]) {     //  Call the hypotenuse method     System.out.println("hypotenuse is " +             StaticDemo.hypotenuse(3.0, 4.0));   } } 

Output ”

 hypotenuse is 5.0 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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