Java 程序实现私有构造函数
javaobject oriented programmingprogramming更新于 2024/4/15 15:40:17
在本文中,我们将了解如何实现私有构造函数。私有构造函数允许我们限制类的实例化。
下面是相同的演示 −
输入
假设我们的输入是 −
Run the program
输出
所需的输出将是 −
正在调用私有构造函数
算法
步骤 1 - 开始 步骤 2 - 我们使用 ‘private’ 关键字定义私有构造函数。 步骤 3 - 将构造函数设为私有可确保无法创建该类的对象。 步骤 4 - 私有构造函数可与同一类内的静态函数一起使用。 步骤 5 - 私有构造函数通常用于单例设计模式。 步骤 6 - 在主方法中,我们使用打印语句来调用静态方法。 步骤 7 - 然后它在控制台上显示输出。
示例 1
Here, the input is being entered by the user based on a prompt.
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
这里调用了 private instructor 并调用了一个实例。
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 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

