ตัวแปรมีสามประเภทที่คลาสสามารถมีใน Java ได้คือ ตัวแปรภายในเครื่อง ตัวแปรอินสแตนซ์ และ คลาส/สแตติก ตัวแปร
ตัวแปรในเครื่อง
A ตัวแปรท้องถิ่น ใน Java สามารถประกาศในเครื่องใน วิธีการ , บล็อคโค้ด, และ ตัวสร้าง . เมื่อโปรแกรมควบคุมเข้าสู่ วิธีการ บล็อกโค้ด และ ตัวสร้าง จากนั้นตัวแปรท้องถิ่นจะ สร้าง และเมื่อโปรแกรมควบคุมออกจากเมธอด โค้ดบล็อก และตัวสร้าง ตัวแปรในเครื่องจะ ถูกทำลาย . ตัวแปรท้องถิ่น ต้องเริ่มต้น มีค่าบ้าง
ตัวอย่าง
public class LocalVariableTest {
public void show() {
int num = 100; // local variable
System.out.println("The number is : " + num);
}
public static void main(String args[]) {
LocalVariableTest test = new LocalVariableTest();
test.show();
}
} ผลลัพธ์
The number is : 100
ตัวแปรอินสแตนซ์
ตัวอย่าง ตัวแปร e ใน Java สามารถประกาศ นอกบล็อก , วิธีการ หรือ ตัวสร้าง แต่ในชั้นเรียน ตัวแปรเหล่านี้ สร้าง เมื่อคลาส วัตถุถูกสร้างขึ้น และ ทำลาย เมื่อคลาส วัตถุถูกทำลาย .
ตัวอย่าง
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[]) {
InstanceVariableTest test = new InstanceVariableTest(75);
test.show();
}
} ผลลัพธ์
The number is : 75
ตัวแปรคงที่/คลาส
A ตัวแปรสแตติก/คลาส สามารถกำหนดได้โดยใช้ คงที่ คำสำคัญ. ตัวแปรเหล่านี้ถูกประกาศในคลาส แต่ นอกวิธีการ และ บล็อคโค้ด . ตัวแปรคลาส/สแตติกสร้าง .ได้ เมื่อ เริ่มโปรแกรม และ ทำลาย ที่ สิ้นสุดโปรแกรม .
ตัวอย่าง
public class StaticVaribleTest {
int num;
static int count; // static variable
StaticVaribleTest(int n) {
num = n;
count ++;
}
public void show() {
System.out.println("The number is: " + num);
}
public static void main(String args[]) {
StaticVaribleTest test1 = new StaticVaribleTest(75);
test1.show();
StaticVaribleTest test2 = new StaticVaribleTest(90);
test2.show();
System.out.println("The total objects of a class created are: " + count);
}
} ผลลัพธ์
The number is: 75 The number is: 90 The total objects of a class created are: 2