class Test3 { private Test3 a=new Test3(); //private static Test3 a=new Test3(); public static void main(String[] args) { Test3 t = new Test3(); } public Test3 getA() { return a; } public void setA(Test3 a) { this.a = a; } }
?第而种情况,自己调用自己,并迭代,生成新的对象;
结果 Exception in thread "main" java.lang.StackOverflowError;
class Test4 { private static Test4 a=new Test4(); public static void main(String[] args) { Test4 t = new Test4(); System.out.println(t.getA()); System.out.println(t.getA().getA()); System.out.println(t.getA().getA().getA()); } public Test4 getA() { return a; } public void setA(Test4 a) { this.a = a; } }
?
第三种情况,没有报错,因为生成了静态对象,结果
com.b5map.Test4@6084fa6a
com.b5map.Test4@6084fa6a
com.b5map.Test4@6084fa6a
?
总结:static关键字,只保留自己唯独一份的变量;而且对自身的引用始终是自己;
?
?
?