클래스 내부에 선언된 배열 변수는 다른 일반 값과 마찬가지로 생성자(Constructor) 또는 Setter 메서드를 사용하여 초기화할 수 있습니다. 두 가지 방법 모두 객체가 생성된 후 배열 데이터를 필드에 할당하는 방식이며, 상황에 따라 적합한 방법을 선택하면 됩니다.
예제 1: 생성자를 이용한 배열 초기화
다음 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: Setter 메서드를 이용한 배열 초기화
생성자 대신 Setter 메서드를 활용하면 객체를 기본 생성자로 만든 뒤, 필요한 시점에 각 필드의 값을 설정하거나 변경할 수 있습니다. 아래 예제는 setName(), setAge(), setSubs() 메서드를 통해 이름, 나이, 과목 배열을 순차적으로 할당하는 방식을 보여줍니다.
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
정리하면, 생성자를 사용하는 방법은 객체 생성과 동시에 배열을 초기화해야 하는 경우에 적합하고, Setter 메서드를 사용하는 방법은 객체 생성 이후에 값을 유연하게 설정하거나 수정해야 하는 경우에 유용합니다. 두 방식 모두 배열 참조를 그대로 전달하기 때문에, 호출 전에 배열이 이미 초기화되어 있어야 한다는 점에 유의하세요.