views:

491

answers:

15

For quite some time, I have been unsure about what the Keyword "Static" does while it is used in OOP.

I know that if we define a static variable, the value remains the same through out all instances of that class, what does it do when it is used with class or method.

I mean, What is a static method and Static class? On what condition are they appropriate to use? Should I avoid using static method or class or prefer it?

What does keyword Static actually symbolizes?

Please include answers in all possible languages? Examples would be deeply appreciated for both static method and static class.

+2  A: 

They should be used where it is not necessary to initiate an instance of the class yourself.

Some examples are

  • factory methods that return an instance of the object
  • as a way to namespace in some languages where their support is not commonplace (like PHP, for example html::anchor('text'))
alex
Whoops, where am I wrong so I can learn something?
alex
+2  A: 

It indicates that the member is accessed via the class itself, rather than via an instance.

Ignacio Vazquez-Abrams
+8  A: 

In C++, a static method is not associated with an instance of the class. Therefore you neither need an instance to call the method nor can the method access any instance data:

class foo
{
public:
    int method();
    static int smethod();

private:
    int field;
};

To call method, you first need an instance of foo:

foo f;
int x = f.method();

You can call smethod without having an instance:

int y = foo::smethod();

Note that you can also call smethod like an instance method but that's just a convenience:

int z = f.smethod();  // legal, but smethod has no access to the f instance
                      // such as 'field'
R Samuel Klatchko
A: 

In C#
A good candidate for a static method is one that doesn't use any instance data/members of the containing type. Some behavior that is common for all instances of the containing type. You access it via a TypeName.StaticMethod( args ) syntax.

A good candidate for a static Class is a container for shortcut methods, extension methods. A class that you want to house a cohesive set of 'global' methods. Static classes can't be instantiated, derived or have instance members defined in it. It is syntactical sugar + compiler checks for 'abstract and sealed with no instance members'

For an example in the .Net framework, look at the File type (static class) and its members (static methods).

Gishu
+3  A: 

Although you didn't specify a language, here is an explanation using C# as a base language. Since it is OOP though, it follows the abstract ideas fairly closely.

Static Classes

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:

  1. They only contain static members.
  2. They cannot be instantiated.
  3. They are sealed.
  4. They cannot contain Instance Constructors.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state.

Static Methods

A static method, field, property, or event is callable on a class even when no instance of the class has been created.

If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

Reference

Sev
Not your fault, but I did LOL at the juxtaposition of 'C# is an OO language' and your static class which you can't create any objects from.
Pete Kirkham
A: 

Static means, this method/variable will remain same for the whole application lifetime.

For instance you can provide a static class method that would convert word to pdf. Or insert records in database based upon input arguments, etc. statics can be called directly to operate upon.

KMan
A: 

Pseudo code:

Static class:

Public Static class foo{
    Public Static metod bar(){

    }
}

Non static class

Public class foo{
    Public metod bar(){

    }
}

In the first example youcan call the method bar() from anywhare in the code by simply typing foo.bar(). But in the second example you need to have an instance of foo first like so:

f = new foo()
f.bar()
Charlie boy
A: 

Whenever I think of a static method, I only have to think of Math.sqrt. You don't need to create a new Math instance to run it; rather, the sqrt method belongs to the Math class itself, and not to an instance of it.

Similarly, Math.pi. It's not an instance variable of any instance of Math. It's a variable (or technically, a constant) of the class itself.

Justin L.
+2  A: 

In C - There are essentially three uses of the word 'static'. It is important to note here that the usage is slightly different from C++, due to the non-existence of classes.

The threes instances of use are:
1) A variable declared as static inside a function.
2) A variable declared as static at the file scope level, accessible to all functions in that file.
3) A function defined as 'static' within a .c file.

Explanation or usage:

First Case:

The first one is most commonly used in projects and is fairly well understood. It relates to a variable retaining its value between function invocations. i.e if you have:

 void foo()
 {
     static uint8_t testingStaticVariable = 0;
     testingStaticVariable += 1;
     printf("Value of Static variable is %d", testingStaticVariable);
 }
 void main()
 {
     for(int i = 0; i < 3; i++)
     {
          foo(); // Called three times. 
     }
 } 

For the above mentioned sample program, you will find that the testingStaticVariable will retain its value everytime foo() is called. Therefore the output would look like this:
Value of Static variable is 1
Value of Static variable is 2
Value of Static variable is 3

Therefore you can see that by defining the variable as static it retained it's value between the multiple invocations of foo.

Second case:

Defining a variable as 'static' in a example.c file simply means that all functions within that example.c file have access to alter the contents of this variable. However, any functions that might include the header file example.h for this example.c file, will not have access to this variable.

This is also sometimes known as localised global.

Third case:

This is probably the least used, but is extremely useful, if one knows how to utilize this feature. There are no access specifiers for the C programming language. i.e there are no functions you can declare private or public. However, you can almost achieve the same level of protection, by declaring functions as static. If you declare a function as static within a .c file, only other functions within that .c file can see/access this function, whereas the interface or the header file .h will not contain these function prototypes, and therefore, any files within the project that might include the header file, will still not have access to the 'private' (by declaring them as static) functions defined in the .c file.

This achieves some level of protection or abstraction, that is really useful in large projects, where you want to be able to provide an interface (via the header file) to this .c file or more appropriately referred to as a compilation unit, but do not want to expose other functions defined within this compilation unit.

So essentially you are localising the scope of these functions to a particular compilation unit, such that even though other modules might have access to this module, they will be unable to see these functions.

Typically the way to achieve this is: You would have: an interface file (visible to everyone in the project) called example.h a source file that contains the implementation of the interface, called example.c

//example.h
#ifndef EXAMPLE_H
#define EXAMPLE
_H

 void doSomethingImp();  

 #endif

//example.c

// global variable definition
uint8_t exampleVariable = 0;

// local function prototypes declared here as static, not visible outside example.c
static void setVariable(uInt8_t num);
static uint8_ t geVariable();


void doSomethingImp()
{
    //lets do something here with a variable.
     uint8_t foo = 0;
     setVariable(5);
     foo = getVariable();
}

static void setVariable(uInt8_t num)
{
     exampleVariable = num;
}

static uint8_ t geVariable()
{ 
     return exampleVariable;
}

Now in the above mentioned sample project, if another foo.c included example.h, it would only have access to the doSomethingImp() function. It WOULD NOT HAVE access to the setVariable(uInt8_t num) and the geVariable() functions since they were declared as static, which localised their scope to the example.c compilation unit.

IntelliChick
A: 

Static does not exist in object oriented programming. It exists as a convenience to lessen the jump from imperative or functional code, and each use of static is in effect a singleton - in effect you can directly write every static function as a free function (not associated with a class) in languages which support them, or you can refactor them as a call to an instance of a class which has the same fields as you have static variables (an OO approach). They are used as it is more convenient to have something which is in effect a free function but has the same scope as a class.

See this discussion by Gilead Bracha as how to replace the use of static with object oriented design.

Pete Kirkham
A: 

In PHP

Static Keyword

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).

http://php.net/manual/en/language.oop5.static.php

learner
A: 

First, static is not a generic OOP term. it is language specific. So lets focus and talk about static in C++

First thing first, know that the static word has first appeared in C, and had kept it original meaning, when you place it outside of a class.

C static examples:

First meaning, something like global variable in a local scope:

void foo() {
   static int counter = 0 ;
   counter++;
}

the counter variable life is global - each call will increment it (call foo() three times, and it's value would be 3). But, it has a local scope - no other function (except foo) can access it.

Another C meaning of the word static, is to make a variable or a function visible only in the current compilation unit.

example:

int globalVar;
static int fileVar;

In this example globalVar is a global variable, which can be accessed throughout the program. the fileVar can only be accessed in the C file it was defined in.

New C++ meanings to the word static:

In C++ (and other languages too) static means "Belonging to the class" instead of the usual "Belonging to an object (instance of the class)".

Example:

class Foo { 
private:
  static int classVar;
public:
  static int getClassVar() {return classVar;}
};

In this example the classVar is static class member. It is essentialy like a global C variable - but it belongs to a class and you can set access (private, public...) to it.

The static method getClassVar is like a C function, but it belongs to a class and can access private static members and methods.

uvgroovy
A: 

In C++, static is the most overloaded keyword with barely-related meanings. Static variable in a function (persistence), static global variable (cross-module accessibility), static data member and static method (out-of-instance lifetime), static_cast (compile-time known cast algorithm). What do these have in common? keyword 'static'.

Pavel Radzivilovsky
A: 

Use of Static

"Static" keyword is one of very useful keyword, which can be applied to those function which are just taking values from parameters and perform operation on values and retun result (like: mathematical functions, any calculation function, conversion function or any such kind) static functions can be used to provide utility functions to a class so when we declare such a functions as "static" then, we need not to create an object for calling such functions , we can directly use them with class name and pass values in it and get result.

Static Variables: static type variables are used where we want to maintain a single copy of value for all object of class. we create static variable in such a situation like we are developing a shopping cart application and lets assume we want to fix the "DISCOUNT" for all function in shopping cart, in such a situation we can take static double/float variable and set value in it and all functions will use same value and when we will change its value (in certain situation) the changes will be reflected to all those functions which are using it. and when ever we will extend application and create new function at that time without thinking of creating object and setting value of discount in it, we can directly use that static variable with class name.

http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-static-functions.html

Rajesh Rolen- DotNet Developer
A: 

a simple concept would be.... a variable eg,x is single have only one reference ....any changes made to x from any part of the program will be reflected directly on x...and if viewed from any part of the program would result in the changed value.so its a lonely global type of variable :)

ankish