কম্পিউটার

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


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

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

প্যারামিটারাইজড কনস্ট্রাক্টর

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

উদাহরণ

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

  1. কিভাবে জাভাতে ডিরেক্টরি (ক্রমানুসারে) তৈরি করবেন?

  2. কিভাবে জাভা 9 এ ProcessBuilder ব্যবহার করে একটি প্রক্রিয়া তৈরি করবেন?

  3. জাভা 9 এ এইচটিএমএল 5 অনুগত জাভাডোক কীভাবে তৈরি করবেন?

  4. কীভাবে জাভাতে একটি অস্থায়ী ফাইল তৈরি করবেন