プライベートコンストラクタを実装する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
-
正方形の領域を見つけるJavaプログラム
この記事では、正方形の面積を見つける方法を理解します。正方形の面積は、次の式を使用して計算されます- side*side i.e. s2 以下は同じのデモンストレーションです- 正方形の辺がsの場合、正方形の面積はs 2で与えられます。 − 入力 入力が-であると仮定します Length of the side : 4 出力 必要な出力は-になります Area of the square : 16 アルゴリズム Step 1 - START Step 2 - Declare 2 integer values namely my_side and my_area. S
-
Javaで数を数えるプログラムを実装するにはどうすればよいですか?
プログラムはJLabelを使用します カウントラベルを保持するには、 JTextField 数値を保持するコンポーネントカウント 、 JButton 追加を作成するコンポーネント 、削除 およびリセット ボタン。追加ボタンをクリックすると、JTextFieldのカウントがインクリメントされます 投稿者 1 削除ボタンをクリックすると、カウントが「1」ずつ減らされます。 [リセット]ボタンをクリックすると、リセットされます 0へのカウント 。 例 import java.awt.*; import java.awt.event.*; import javax.swing.*; publ