Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อใช้งานคอนสตรัคเตอร์ส่วนตัว


ในบทความนี้ เราจะเข้าใจวิธีการใช้ตัวสร้างส่วนตัว ตัวสร้างส่วนตัวช่วยให้เราสามารถจำกัดการสร้างอินสแตนซ์ของคลาสได้

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

ป้อนข้อมูล

สมมติว่าข้อมูลที่เราป้อนคือ −

Run the program

ผลผลิต

ผลลัพธ์ที่ต้องการจะเป็น −

Private constructor is being called

อัลกอริทึม

Step 1 - Start
Step 2 - We define a private constructor using the ‘private’ keyword.
Step 3 - Making a constructor private ensures that an object of that class can’t be created.
Step 4 - A private constructor can be used with static functions which are inside the same class.
Step 5 - The private constructor is generally used in singleton design pattern.
Step 6 - In the main method, we use a print statement to call the static method.
Step 7 - It then displays the output on the console.

ตัวอย่างที่ 1

ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง

class PrivateConstructor {
   private PrivateConstructor () {
      System.out.println("A private constructor is being called.");
   }
   public static void instanceMethod() {
      PrivateConstructor my_object = new PrivateConstructor();
   }
}
public class Main {
   public static void main(String[] args) {
      System.out.println("Invoking a call to private constructor");
      PrivateConstructor.instanceMethod();
   }
}

ผลลัพธ์

Invoking a call to private constructor
A private constructor is being called.

ตัวอย่างที่ 2

ที่นี่ผู้สอนส่วนตัวถูกเรียกและอินสแตนซ์ถูกเรียก

import java.io.*;
class PrivateConstructor{
   static PrivateConstructor instance = null;
   public int my_input = 10;
   private PrivateConstructor () { }
   static public PrivateConstructor getInstance(){
      if (instance == null)
      instance = new PrivateConstructor ();
      return instance;
   }
}
public class Main{
   public static void main(String args[]){
      PrivateConstructor a = PrivateConstructor .getInstance();
      PrivateConstructor b = PrivateConstructor .getInstance();
      a.my_input = a.my_input + 10;
      System.out.println("Invoking a call to private constructor");
      System.out.println("The value of first instance = " + a.my_input);
      System.out.println("The value of second instance = " + b.my_input);
   }
}

ผลลัพธ์

Invoking a call to private constructor
The value of first instance = 20
The value of second instance = 20