Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

개인 생성자를 구현하는 Java 프로그램

<시간/>

이 기사에서는 private 생성자를 구현하는 방법을 이해할 것입니다. 개인 생성자를 사용하면 클래스의 인스턴스화를 제한할 수 있습니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
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