“static” Keyword in Programming Languages

Many programming languages have integrated the notion of “static” into their nomenclature. Most of the “Object Oriented“ languages have integrated it as “class variable” (as opposed to instance variable).

Now, if we want to describe the notions of class and instance variables we would say a class variable is instantiated when first a type is referenced via the static members or when first instance is created (.Net and Java is like that) or type is loaded into the memory (C\C++ is like that). An instance variable, on the other hand, is created when any of the class constructors is called.

There is also the notion of “static class constructor“s. In .Net you would create one as:

sealed class MyObj
{
      static MyObj()
      {
            //Access static members and initiate
      }
}

In Java, this is accomplished with “static block“s. It is the same as its .Net counterpart, only the syntax is different.

final class MyObj
{
      static
      {
            //Access static members and initiate
      }
}

In C\C++, it is a bit different tough. “static” is either a “storage class” definition or is the same as above. If it modifies a variable in the top level (out side of any function call and any “class” definition) then the variable it defines will be visible to the file only. There no similarity to the “static” word in the other languages for this use. For example, below is a header file, named “myinclude.h”:

#ifndef _MYINCLUDE_H_
#define _MYINCLUDE_H_

static uint mynumber = 0;

#endif

In this file, “mynumber” will only be visible to this file and the files that include “myinclude.h”.

On the other hand, in C++, if a “static” variable is defined inside of a “class” then it is the same usage with C# or Java.

struct Request {
      static int count;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>