Java:
1) static class variable:
Class variables which have static modifier in their declaration are static class variables.
- Associated with class, not instances of the class.
- No matter how many objects are created for that class, the static variable will be common for all, residing in one fixed location in memory.
- Any object can change its value.
- Can be accessed directly without using object. Syntax: <class_name>.<static_variable_name>
- Useful for tasks like keeping count of how many instances of a class have been created.
- Can be accessed without object, directly using <class_name>.<static_method_name>(args) construct.
- If a static variable is used inside a method, that method HAS to be static.
- Very useful because they can be invoked without creating object. It can be very expensive to create an object of an extensive class, if this method is all that is going to be used.
- Code in a static method can only use static variables and the parameters that the method accepts.
- It is not allowed to declare a static variable inside a method, even if the method is static. In C/C++, this is allowed.
- A variable which is made static final is a global constant.
- Its value cannot change.
- Example: static final float PI = 3.14;
4) static class
A class can be a static class only if it is declared inside the top level class. Prefixing the keyword static to the class declaration makes it accessible outside the top level class as well. For example, if the main class is Car and nested class is Sedan, then from outside the main class:
Car c = new Car();
c.newCar(new Car.Sedan(...));
See here for more details: http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html
C++:
1) static variable (not a class variable)
- Allocated when the program starts, and deallocated when it ends.
- Automatically initialized to zero, unless defined otherwise.
- Value of a static variable in a function is retained in spite of repeated calls to the function.
- A static variable is accessible throughout that file of code, but other files cannot see this variable.
- Same as above, except that it cannot be initialized in class itself. Example:
public:
static int value;
};
int SomeRandomName::value = 999;
- You are required to initialize the static class variable, or it will not be in scope.
3) static function (class method)
- A static class method is accessed directly using class name and scope resolution operator.
- When it is called for the first time, an instance of the class is made available.
- A static member function does not have a this pointer.
- Cannot access non-static members of the class in which it is declared.
0 comments:
Post a Comment