第一种:
class A{
private A(){}
private static A A1=new A();
public static A getA1() {
return A1;
}
}
在main函数中:
public static void main(String[] args) {
A s1=A.getA1();
A s2=A.getA1();
System.out.println(s1==s2);
}
输出true。
第二种:
class B{
private B(){}
private static B B1;
public static B getB1() {
if(B1==null){
B1=new B();
}
return B1;
}
}
在main函数中:
public static void main(String[] args) {
B s1=B.getB1();
B s2=B.getB1();
System.out.println(s1==s2);
}
输出true。
第三种
private C(){}
private static class Inner{
public static C C1=new C();
}
public static C getC1(){
return Inner.C1;
}
public static void display(){}
}
在main函数中:
public static void main(String[] args) {
C s1=C.getC1();
C s2=C.getC1();
System.out.println(s1==s2);
}
输出true。
第四种:
enum D{
D1;
public void show(){
System.out.println("show()");
}
}
在main函数中:
public static void main(String[] args) {
D1.
show();
}
输出show()。