Core Java - [Static Members]

♠ Posted by Unknown in at 23:35

Static Members

A class basically contains two sections. One declares variables and the other declares methods. These variables and methods are called instance variables and instance methods. This is because every time the class is instantiated, a new copy of each of them is created. They are accessed using the objects (with dot operator).

Let us assume that we want to define a member that is common to all the objects and accessed without using a particular object. That ism the member belongs to the class as whole rather than the objects created from the class. Such members can be defined as follows:

            static int count;
            static int max(int x, int y);

The members that are declared static as shown above are called static members. Since these members are associated with the class itself rather than individual objects, the static variables and static methods are often referred to as class variables and class methods in order to distinguish
them from their counterparts, instance variables and instance methods. Static variables are used when we want to have a variable common to all instances of a class.

Like static variables, static methods can be called without using the objects. they are also available for use by other classes. Methods that are of general utility but do not directly affect an instance of that class are usually declared as class methods. Java class library defines many static methods to perform math operations that can be used in any program.
Example:

//Save This file with the name of class which have main() method.
import java.lang.*;
import java.io.*;
class MathOperation
{
            static double mul(double x, double y)
            {
                        return x*y;
            }
            static double divide(double x, double y)
            {
                        return x/y;
            }
}
class MathApplication
{
            public static void main(String [] args)
            {
                        double a = MathOperation.mul(4.0, 5.0);
                        double b = MathOperation.divide(a, 2.0);
                        System.out.println("b = " + b);
            }
}

Note that the static methods are called using class names. In fact, no objects have been created for use. 

Static methods have several restrictions. 
  1. They can only call other static methods.
  2. They can only access static data.
  3. They cannot refer to “this” or “super” in any way.

0 comments:

Post a Comment