কম্পিউটার

জাভাতে প্যারামেট্রাইজড কনস্ট্রাক্টরের ব্যবহার কী?


একটি কনস্ট্রাক্টর পদ্ধতির অনুরূপ এবং এটি ক্লাসের একটি অবজেক্ট তৈরি করার সময় আহ্বান করা হয়, এটি সাধারণত একটি ক্লাসের ইনস্ট্যান্স ভেরিয়েবল শুরু করতে ব্যবহৃত হয়। কনস্ট্রাক্টরদের তাদের ক্লাসের মতো একই নাম আছে এবং, কোন রিটার্ন টাইপ নেই।

প্যারামিটারাইজড কনস্ট্রাক্টর এবং নো-আর্গ কনস্ট্রাক্টর দুই ধরনের কনস্ট্রাক্টর আছে প্যারামিটারাইজড কনস্ট্রাক্টর প্যারামিটার গ্রহণ করে।

কনস্ট্রাক্টরের প্রধান উদ্দেশ্য হল ক্লাসের ইনস্ট্যান্স ভেরিয়েবল শুরু করা। একটি প্যারামিটারাইজড কনস্ট্রাক্টর ব্যবহার করে, আপনি ইনস্ট্যান্স ভেরিয়েবলগুলি ইনস্ট্যান্সের সময় নির্দিষ্ট করা মানগুলির সাথে গতিশীলভাবে শুরু করতে পারেন৷

public class Sample{
   Int i;
   public sample(int i){
      this.i = i;
   }
}

উদাহরণ

নিম্নলিখিত উদাহরণে ছাত্র শ্রেণীর দুটি ব্যক্তিগত ভেরিয়েবল আছে বয়স এবং নাম। প্রধান পদ্ধতি থেকে আমরা প্যারামিটারাইজড কনস্ট্রাক্টর −

ব্যবহার করে ক্লাস ভেরিয়েবলকে ইনস্ট্যান্টিয়েটিং করছি
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

  1. জাভাতে অবজেক্ট ক্লোনিংয়ের ব্যবহার কী?

  2. জাভাতে স্ট্রিক্টম্যাথ ক্লাসের ব্যবহার কী?

  3. জাভাতে setBounds() পদ্ধতির ব্যবহার কি?

  4. কনস্ট্রাক্টরের নাম জাভাতে ক্লাসের নামের মতো কেন?