생성자는 메소드와 유사하며 클래스의 객체를 생성할 때 호출되며 일반적으로 클래스의 인스턴스 변수를 초기화하는 데 사용됩니다. 생성자는 클래스와 이름이 같으며 반환 유형이 없습니다.
매개변수화된 생성자와 인수가 없는 생성자에는 두 가지 유형이 있습니다.
매개변수화된 생성자
매개변수화된 생성자는 인스턴스 변수를 초기화할 수 있는 매개변수를 허용합니다. 매개변수화된 생성자를 사용하여 고유한 값으로 클래스를 인스턴스화할 때 클래스 변수를 동적으로 초기화할 수 있습니다.
예시
public class StudentData {
private String name;
private int age;
public StudentData(String name, int age){
this.name = name;
this.age = age;
}
public StudentData(){
this(null, 0);
}
public StudentData(String name) {
this(name, 0);
}
public StudentData(int age) {
this(null, 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[]) {
//Reading values from user
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(" ");
//Calling the constructor that accepts both values
System.out.println("Display method of constructor that accepts both values: ");
new StudentData(name, age).display();
System.out.println(" ");
//Calling the constructor that accepts name
System.out.println("Display method of constructor that accepts only name: ");
new StudentData(name).display();
System.out.println(" ");
//Calling the constructor that accepts age
System.out.println("Display method of constructor that accepts only age: ");
new StudentData(age).display();
System.out.println(" ");
//Calling the default constructor
System.out.println("Display method of default constructor: ");
new StudentData().display();
}
} 출력
Enter the name of the student: Krishna Enter the age of the student: 22 Display method of constructor that accepts both values: Name of the Student: Krishna Age of the Student: 22 Display method of constructor that accepts only name: Name of the Student: Krishna Age of the Student: 0 Display method of constructor that accepts only age: Name of the Student: null Age of the Student: 22