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

ประเภทตัวแปรที่คลาสสามารถมีได้ใน Java

ใน Java คลาสสามารถมีตัวแปรได้ 3 ประเภท ได้แก่ Local Variables, Instance Variables, และ Class/Static Variables

1. Local Variable (ตัวแปรท้องถิ่น)

ประกาศใน เมธอด, บล็อกโค้ด, คอนสตรัคเตอร์ สร้างเมื่อเข้าสcope ทำลายเมื่อออกจาก scope ต้องกำหนดค่าเริ่มต้น (initialize) ก่อนใช้งาน

ตัวอย่าง

public class LocalVariableTest {
    public void show() {
        int num = 100; // local variable
        System.out.println("The number is: " + num);
    }
    public static void main(String args[]) {
        new LocalVariableTest().show();
    }
}
The number is: 100

2. Instance Variable (ตัวแปรอินสแตนซ์)

ประกาศ นอกเมธอด/บล็อก/คอนสตรัคเตอร์ แต่ในคลาส สร้างเมื่อ สร้างอ็อบเจกต์ ทำลายเมื่อ ทำลายอ็อบเจกต์ แต่ละอินสแตนซ์มีค่าของตัวเอง

ตัวอย่าง

public class InstanceVariableTest {
    int num; // instance variable
    InstanceVariableTest(int n) { num = n; }
    public void show() { System.out.println("The number is: " + num); }
    public static void main(String args[]) {
        new InstanceVariableTest(75).show();
    }
}
The number is: 75

3. Static/Class Variable (ตัวแปรสแตติก/คลาส)

ประกาศด้วย static อยู่ ในคลาสแต่นอกเมธอด/บล็อก สร้างตอน เริ่มโปรแกรม ทำลายตอน จบโปรแกรม แชร์ร่วมกันทุกอินสแตนซ์

ตัวอย่าง

public class StaticVariableTest {
    int num;
    static int count; // static variable
    StaticVariableTest(int n) { num = n; count++; }
    public void show() { System.out.println("The number is: " + num); }
    public static void main(String args[]) {
        StaticVariableTest t1 = new StaticVariableTest(75); t1.show();
        StaticVariableTest t2 = new StaticVariableTest(90); t2.show();
        System.out.println("Total objects created: " + count);
    }
}
The number is: 75
The number is: 90
Total objects created: 2

สรุป: Local=ในเมธอด, Instance=ต่ออ็อบเจกต์, Static=ต่อคลาส (แชร์ร่วมกัน)