Java中怎么让一个类只能生成一个对象

2025-12-13 02:09:59
推荐回答(3个)
回答1:

用单例模式
其中的构造方法私有,而且变量是本身类型(私有,静态),写一个get方法来获得这个对象,return的这个类的对象

回答2:

class Rect

{
private static Rect rect = null;
int width, height;

private Rect() {
width = 10;
height = 20;
}

public static Rect getRect() {
if (rect == null) {
rect = new Rect();
System.out.println(rect.width);
System.out.println(rect.height);

}
return rect;
}
}

public class Class_aaaaText {
public static void main(String args[]) {
Rect.getRect();
}
}

回答3:

if(Rect rect==null){

改为 if(rect==null){