static keyword in C++ vs Java

C++Java 8Server Side ProgrammingProgramming

In C++ or Java we can get the static keyword. They are mostly same, but there are some basic differences between these two languages. Let us see the differences between static in C++ and static in Java.

The static data members are basically same in Java and C++. The static data members are the property of the class, and it is shared to all of the objects.

Example

public class Test {
   static int ob_count = 0;
   Test() {
      ob_count++;
   }
   public static void main(String[] args) {
      Test object1 = new Test();
      Test object2 = new Test();
      System.out.println("The number of created objects: " + ob_count);
   }
}

Output

The number of created objects: 2

Example

#include<iostream>
using namespace std;
class Test {
   public:
      static int ob_count;
      Test() {
         ob_count++;
      }
};
int Test::ob_count = 0;
int main() {
   Test object1, object2;
   cout << "The number of created objects: " << Test::ob_count;
}

Output

The number of created objects: 2

The static member functions - In C++ and Java, we can create static member functions. These are also member of that class. There are some restrictions also.

  • The static methods can only call some other static methods.
  • They can only access the static member variables
  • They cannot access the ‘this’ or ‘super’ (for Java only)

In C++ and Java, the static members can be accessed without creating some objects

Example

//This is present in the different file named MyClass.java
public class MyClass {
   static int x = 10;
   public static void myFunction() {
      System.out.println("The static data from static member: " + x);
   }
}
//This is present the different file named Test.Java
public class Test {
   public static void main(String[] args) {
      MyClass.myFunction();
   }
}

Output

The static data from static member: 10

Example

#include<iostream>
using namespace std;
class MyClass {
   public:
      static int x;
      static void myFunction(){
         cout << "The static data from static member: " << x;
      }
};
int MyClass::x = 10;
int main() {
   MyClass::myFunction();
}

Output

The static data from static member: 10

The static block: In Java we can find the static block. This is also known as static clause. These are used for static initialization of a class. The code, which is written inside the static block, will be executed only once. This is not present in C++

In C++ we can declare static local variables, but in Java the static local variables are not supported.

raja
Published on 08-May-2019 12:43:23
Advertisements