생성자는 메소드와 유사하며 클래스의 객체를 생성할 때 호출되며 일반적으로 클래스의 인스턴스 변수를 초기화하는 데 사용됩니다. 생성자는 클래스와 이름이 같으며 반환 유형이 없습니다.
매개변수화된 생성자와 매개변수가 없는 생성자가 매개변수를 받는 생성자에는 두 가지 유형이 있습니다.
생성자의 주요 목적은 클래스의 인스턴스 변수를 초기화하는 것입니다. 매개변수화된 생성자를 사용하여 인스턴스화 시 지정된 값으로 인스턴스 변수를 동적으로 초기화할 수 있습니다.
public class Sample{
Int i;
public sample(int i){
this.i = i;
}
} 예
다음 예제에서 Student 클래스에는 두 개의 개인 변수 age와 name이 있습니다. main 메소드에서 우리는 매개변수화된 생성자를 사용하여 클래스 변수를 인스턴스화하고 있습니다 -
import java.util.Scanner;
public class StudentData {
private String name;
private int age;
//parameterized constructor
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[]) {
//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 parameterized constructor
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