คุณสามารถเริ่มต้นตัวแปรอาร์เรย์ที่ประกาศไว้ภายในคลาสได้เช่นเดียวกับค่าอื่นๆ ไม่ว่าจะใช้ตัวสร้างหรือใช้วิธีเซ็ตเตอร์
ตัวอย่าง
ในตัวอย่าง Java ต่อไปนี้ เรากำลังประกาศตัวแปรอินสแตนซ์ของประเภทอาร์เรย์และเริ่มต้นจากตัวสร้าง
public class Student {
String name;
int age;
String subs[];
Student(String name, int age, String subs[]){
this.name = name;
this.age = age;
this.subs = subs;
}
public void display() {
System.out.println("Name: "+this.name);
System.out.println("Age :"+this.age);
System.out.print("Subjects: ");
for(int i = 0; i < subs.length; i++) {
System.out.print(subs[i]+" ");
}
}
public static void main(String args[]) {
String subs[] = {"Mathematics", "English", "Science", "Social"};
Student obj = new Student("Krishna", 25, subs);
obj.display();
}
} ผลลัพธ์
Name: Krishna Age :25 Subjects: Mathematics English Science Social
ตัวอย่าง2
public class Student {
String name;
int age;
String subs[];
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSubs(String[] subs) {
this.subs = subs;
}
public void display() {
System.out.println("Name: "+this.name);
System.out.println("Age :"+this.age);
System.out.print("Subjects: ");
for(int i = 0; i < subs.length; i++) {
System.out.print(subs[i]+" ");
}
}
public static void main(String args[]) {
String subs[] = {"Mathematics", "English", "Science", "Social"};
Student obj = new Student();
obj.setName("Krishna");
obj.setAge(25);
obj.setSubs(subs);
obj.display();
}
} ผลลัพธ์
Name: Krishna Age :25 Subjects: Mathematics English Science Social