Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

this keyword อ้างอิง Static Members ได้หรือไม่ใน Java

ไม่ได้ คำสำคัญ this ไม่สามารถอ้างอิง Static Members ของคลาสได้ เพราะ this อ้างอิงถึงอ็อบเจกต์ปัจจุบัน (current object) ส่วน Static Member ไม่ต้องการอ็อบเจกต์ในการเรียกใช้ เข้าถึงได้โดยตรง ผ่านชื่อคลาส โดยไม่ต้องสร้างอ็อบเจกต์

ตัวอย่าง: เข้าถึง Static Members โดยไม่ใช้ this


public class StaticTest {
    static int a = 50;
    static int b;
    
    static void show() {
        System.out.println("Inside the show() method");
        b = a + 5;
    }
    
    public static void main(String[] args) {
        show(); // เรียก static method โดยตรง
        System.out.println("Value of a: " + a);
        System.out.println("Value of b: " + b);
    }
}

ผลลัพธ์

Inside the show() method
Value of a: 50
Value of b: 55

สรุป: Static members เป็นของคลาส ไม่ใช่ของอินสแตนซ์ เรียกใช้ด้วย ClassName.staticMember หรือชื่อโดยตรงในคลาสเดียวกัน this ใช้กับ Instance Members เท่านั้น