ใน C ++ หรือ Java เราสามารถรับคำสำคัญแบบคงที่ ส่วนใหญ่จะเหมือนกัน แต่มีความแตกต่างพื้นฐานบางอย่างระหว่างสองภาษานี้ ให้เราดูความแตกต่างระหว่างสแตติกใน 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 ไม่รองรับตัวแปรท้องถิ่นแบบคงที่