class A
{
public int i = 20;
private static A aa = new A();
private A()
{
}
public static A getA()
{
return aa;
}
//static 一定是不能省略的
}public class TestStatic_2
{
public static void main(String[] args)
{
A aa1 = A.getA();
A aa2 = A.getA();
aa1.i = 99;
System.out.printf("%d\n", aa2.i);
if(aa1 == aa2)
{
System.out.printf("aa1和aa2相等\n");
}
else
{
System.out.printf("aa1和aa2不相等\n");
}
//A aa1 = new A();
//error如果A类的构造方法是private,则new A()就会报错!
//A aa2 = new A();
}
}不太理解A aa = A.getA()和public static A getA()这两种形式,没这样写过
{
public int i = 20;
private static A aa = new A();
private A()
{
}
public static A getA()
{
return aa;
}
//static 一定是不能省略的
}public class TestStatic_2
{
public static void main(String[] args)
{
A aa1 = A.getA();
A aa2 = A.getA();
aa1.i = 99;
System.out.printf("%d\n", aa2.i);
if(aa1 == aa2)
{
System.out.printf("aa1和aa2相等\n");
}
else
{
System.out.printf("aa1和aa2不相等\n");
}
//A aa1 = new A();
//error如果A类的构造方法是private,则new A()就会报错!
//A aa2 = new A();
}
}不太理解A aa = A.getA()和public static A getA()这两种形式,没这样写过
private static A aa = new A(); //生成一个实例public static A getA()
{
return aa; //返回所生成的实例,这样使得每个使用者用的是同一个实例,减少资源浪费
}
每个类都有静态去,包括静态对象和代码。你new的实例对象是另外一块内存空间。
你这里private static A aa=new A(),只是说在静态区有个引用,指向一个A对象而已。
而你的get方法会返回这个引用。
就这样,没什么深奥的。
class A {
private static A a = null;
private A() {
// do some work
}
public static A getInstance() {
if (a == null) {
a = new A();
}
return a;
}
}
其次 具有静态属性 可以让外界直接访问aa(访问到前必已加载),而不必再去通过它外包类的实例来访问(因为非静态成员变量对象无法脱离外包类实例对象而存在)