一个类只生成一个对象
public class A{
private static A a = new A(); //声明为static是为了确保只有一个对象存在,详见static修饰符private A(){} //构造方法为private,外部无法使用new来创建对象.
public static A getA(){
return a;
}
}
public static void main(String[] args){
A b = new A();//错误做法,无法获取对象
A b = A.getA();//正确做法
}
一个类生成了几个对象
public class two{
private int a=0;
two(){
}
class Student{
private String name;
private int Class;
public void getMessage(){
System.out.print("姓名"+name);
}
Student(String arg0){
this.name = arg0;
++a;
}
public void getnumber(){
System.out.print(a);
}
}
public static void main(String[] arg0){
Student a = new two().new Student("wzm");
Student b = new two().new Student("wzd");
a.getMessage();
b.getnumber();
}
}
代码很low描述了大体意思,意会即可。