Sunday, December 15, 2013

static keyword

Basic information about static: 
1. In general, the static keyword means that the entity to which it is applied is available outside any particular instance of the class in which the entity is declared.
2. A static field (member variable of a class) exists once across all instances of the class.
3. A static method may be called from outside the class without first instantiating the class. Such a reference always includes the class name as a qualifier of the method call.
In java, MyClass.f1()
In c++, MyClass::f1()

Here is the understanding about what static means from another angle:
It's used to create utility tools that are ONLY related to the class to which they're applied to. Basically it's a relationship between these static member functions/utility tools and the class.
In theory, you can create these static member variable / member functions anywhere outside the class. However, since those member functions/variables that are declared as static have no use to other components, so it's better to declare them within the class to which they are useful.

One of advantages to doing so is that these static member functions/utility tools have access to the private/protected member variables via entities of the class. Pay attention to "via entities of the class", the reason is these static member functions can only access static member variables. However, they can access private/protected member variables via entities of the class. In contrast, utility tools that are declared outside the class can't.

For example in c++,

static void MyClass::statc_utility_func(MyClass a)
{
  // access private member variable via entity of class. 
   cout << a.data << endl;   // assuming a.data is a private member variable .
}

void outside_utility_func(MyClass a)
{
   cout << a.data << endl;     //  It will be a compile error 'cause it can't access private members.
}

No comments:

Post a Comment