Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để triển khai các hàm tạo riêng

Trong bài viết này, chúng ta sẽ hiểu cách triển khai các hàm tạo riêng. Các hàm tạo riêng cho phép chúng tôi hạn chế việc khởi tạo một lớp.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Run the program

Đầu ra

Đầu ra mong muốn sẽ là -

Private constructor is being called

Thuật toán

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.

Ví dụ 1

Tại đây, đầu vào đang được người dùng nhập dựa trên lời nhắc.

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();
   }
}

Đầu ra

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

Ví dụ 2

Ở đây, một người hướng dẫn riêng được gọi và một phiên bản được gọi.

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);
   }
}

Đầu ra

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