Local Variables ประกาศใน Methods, Constructors, หรือ Blocks สร้างเมื่อเข้าสู่ Method/Constructor/Block และทำลายเมื่อออกจาก Scope
- ไม่สามารถใช้ Access Modifiers ได้
- มองเห็นได้เฉพาะใน Method/Constructor/Block ที่ประกาศ
- Implement ที่ Stack Level ภายใน
ตัวอย่าง Local Variable
public class Demo {
public void rank() {
int rank = 0; // Local Variable
rank = rank + 7;
System.out.println("Rank = " + rank);
}
public static void main(String[] args) {
Demo d = new Demo();
d.rank();
}
}
ผลลัพธ์
Rank = 7
Global Variables ใน Java
ไม่มี Concept ของ Global Variables ใน Java ตัวแปรที่ใกล้เคียงที่สุดคือ Instance Variables (Fields) และ Class Variables (Static Fields) ที่ประกาศระดับ Class
| ประเภท | Scope | Lifetime | Access Modifier |
|---|---|---|---|
| Local Variable | Method/Block เท่านั้น | ระหว่าง Execution | ไม่ได้ |
| Instance Variable | ทั้ง Class (ผ่าน Instance) | ตลอด Object Life | ได้ (private, protected, public) |
| Class Variable (static) | ทั้ง Class (ผ่าน Class Name) | ตลอด Program Life | ได้ |
Best Practice: ใช้ Instance/Static Variables แทน Global Variables พร้อม Access Modifier ที่เหมาะสม (Encapsulation)