คอนสตรัคเตอร์คล้ายกับเมธอดและถูกเรียกใช้ในเวลาที่สร้างอ็อบเจ็กต์ของคลาส โดยทั่วไปจะใช้เพื่อเริ่มต้นตัวแปรอินสแตนซ์ของคลาส ตัวสร้างมีชื่อเดียวกับคลาสและไม่มีประเภทส่งคืน
มีคอนสตรัคเตอร์สองประเภท คอนสตรัคเตอร์แบบกำหนดพารามิเตอร์ และคอนสตรัคเตอร์แบบไม่มีอาร์ก คอนสตรัคเตอร์แบบกำหนดพารามิเตอร์จะยอมรับพารามิเตอร์
วัตถุประสงค์หลักของคอนสตรัคเตอร์คือการเริ่มต้นตัวแปรอินสแตนซ์ของคลาส เมื่อใช้คอนสตรัคเตอร์แบบกำหนดพารามิเตอร์ คุณสามารถเริ่มต้นตัวแปรอินสแตนซ์แบบไดนามิกด้วยค่าที่ระบุในขณะที่สร้างอินสแตนซ์
public class Sample{
Int i;
public sample(int i){
this.i = i;
}
} ตัวอย่าง
ในตัวอย่างต่อไปนี้ คลาส Student มีตัวแปรส่วนตัวสองตัว age และ ชื่อ จากวิธีการหลัก เรากำลังสร้างอินสแตนซ์ของตัวแปรคลาสโดยใช้ตัวสร้างพารามิเตอร์ -
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