생성자(Constructor)란?
생성자는 메서드와 비슷한 역할을 하며, 클래스의 객체가 생성되는 시점에 자동으로 호출됩니다. 주로 클래스의 인스턴스 변수를 초기화하는 용도로 사용되며, 클래스와 이름이 같고 반환 타입이 없다는 특징이 있습니다.
생성자의 두 가지 종류
Java의 생성자는 크게 두 가지로 나눌 수 있습니다.
- 기본 생성자(No-arg Constructor): 매개변수를 받지 않는 기본 형태의 생성자입니다.
- 매개변수화된 생성자(Parameterized Constructor): 하나 이상의 매개변수를 전달받는 생성자입니다.
매개변수화된 생성자의 목적
생성자의 핵심 목적은 클래스의 인스턴스 변수를 초기화하는 것입니다. 매개변수화된 생성자를 사용하면 객체를 생성하는 시점에 원하는 값을 직접 전달하여 인스턴스 변수를 동적으로 초기화할 수 있습니다.
public class Sample{
int i;
public Sample(int i){
this.i = i;
}
}
위 코드처럼 생성자에서 this 키워드를 사용하면, 매개변수로 전달된 값을 해당 객체의 인스턴스 변수에 할당할 수 있습니다.
실전 예제: 학생 정보 초기화하기
다음 예제에서는 StudentData 클래스가 name과 age라는 두 개의 private 변수를 가지고 있습니다. main 메서드에서는 Scanner로 사용자에게 값을 입력받은 뒤, 매개변수화된 생성자를 통해 객체를 생성하고 초기화합니다.
import java.util.Scanner;
public class StudentData {
private String name;
private int age;
//매개변수화된 생성자
public StudentData(String name, int age){
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
//사용자로부터 값 입력받기
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name of the student: ");
String name = sc.nextLine();
System.out.println("Enter the age of the student: ");
int age = sc.nextInt();
System.out.println(" ");
//매개변수화된 생성자 호출
new StudentData(name, age).display();
}
}
실행 결과
Enter the name of the student: Sundar Enter the age of the student: 20 Name of the Student: Sundar Age of the Student: 20
정리
매개변수화된 생성자를 활용하면 객체 생성과 동시에 필요한 값으로 인스턴스 변수를 초기화할 수 있어, 별도의 setter 호출 없이도 깔끔하고 안전한 코드를 작성할 수 있습니다. 사용자 입력, 파일 데이터, 외부 값 등 다양한 소스로부터 받은 값으로 객체를 만들 때 특히 유용합니다.