C++ 또는 Java에서는 static 키워드를 얻을 수 있습니다. 그것들은 대부분 동일하지만 이 두 언어 사이에는 몇 가지 기본적인 차이점이 있습니다. C++의 정적과 Java의 정적 간의 차이점을 살펴보겠습니다.
정적 데이터 멤버는 기본적으로 Java와 C++에서 동일합니다. 정적 데이터 멤버는 클래스의 속성이며 모든 개체에 공유됩니다.
예시
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);
}
} 출력
The number of created objects: 2
예시
#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;
} 출력
The number of created objects: 2
정적 멤버 함수 - C++ 및 Java에서 정적 멤버 함수를 만들 수 있습니다. 이들도 해당 클래스의 구성원입니다. 몇 가지 제한 사항도 있습니다.
- 정적 메서드는 다른 정적 메서드만 호출할 수 있습니다.
- 정적 멤버 변수에만 액세스할 수 있음
- 'this' 또는 'super'(Java 전용)에 액세스할 수 없습니다.
C++ 및 Java에서는 일부 개체를 생성하지 않고도 정적 멤버에 액세스할 수 있습니다.
예시
//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();
}
} 출력
The static data from static member: 10
예시
#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();
} 출력
The static data from static member: 10
정적 블록:Java에서 정적 블록을 찾을 수 있습니다. 이를 정적 절이라고도 합니다. 이들은 클래스의 정적 초기화에 사용됩니다. 정적 블록 내부에 작성된 코드는 한 번만 실행됩니다. 이것은 C++에 존재하지 않습니다.
C++에서는 정적 지역 변수를 선언할 수 있지만 Java에서는 정적 지역 변수가 지원되지 않습니다.