看到网上一道题目,私有化构造方法后,该类能不能被实例化。答案比较尴尬,直接实例化肯定是不行了,因为构造方法被私有化了,也就意味着在别的类中不能直接实例化该对象了,
难道真的没办法了吗?网上查询了一下资料,恍然大悟,有一种东西叫做静态方法,不需要实例化直接调用。具体实现如下:
public class Person{
private static Person person;
private Person(){
System.out.println("1");
}
public static Person getPerson(){
if(person==null){
person = new Person();
}
return person;
}
}
public class student(){
public static void main(String args[]){
Person person = Person.getPerson();
}
}