Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java.
Similarities between C++ and Java for Static Keyword:
- Static data members can be defined in both languages.
- Static member functions can be defined in both languages.
- Easy access of static members is possible, without creating some objects.
Differences between C++ and Java for Static Keyword:
|C++ doesn’t support static blocks.||Java supports static block (also called static clause). It is used for the static initialization of a class.|
|Static Local Variables can be declared.||Static Local Variables are not supported.|
The above points are discussed are in detail below:
1. Static Data Members: Like C++, static data members in Java are class members and shared among all objects. For example, in the following Java program, the static variable count is used to count the number of objects created.
Total 2 objects created
2. Static Member Methods: In C++ and Java, static member functions can be defined. Methods declared as static are class members and have the following restrictions:
A) They can only call other static methods. For example, the following program fails in the compilation. fun() is non-static and it is called in static main().
B) They must only access static data.
D) Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using the class names. For example, in the following program, static data member count and static method fun() are accessed without any object.
Test.count = 0 Static fun() called
3. Static Block: Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside the static block is executed only once. See Static blocks in Java for details.
4. Static Local Variables: Unlike Java, C++ supports static local variables. For example, the following Java program fails in the compilation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.