类内部实例化自身可行吗?

答案是不能。

事实证明,在类内部一直实例化自身会造成栈溢出,测试代码如下

 1 public class test1 {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         test1.A aa = new test1().new A();
 9         test1.A b = aa.getA();
10         System.out.println("ok");
11     }
12 
13     class A{
14  
15         private A a;
16         
17         public A getA(){
18             a = new A();
19             return a;
20         }
21     }
22 }
这是因为,声明类,可以认为是在类内放一张空白纸,实例化是按照图纸造了一座房子,类内声明自己,只是放了一张A类型的图纸,并没有造房子,不会引起无限调用。
在函数中实例化类,必须调用函数才会执行,因此也不会引起无限调用,所以不会出现错误。
由此,还可以实现单例模式。
单例模式分为懒汉式和饿汉式
懒汉式:
 1 public class test1 {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         test1.A aa = new test1().new A();
 9         test1.A b = aa.getA();
10         System.out.println("ok");
11     }
12 
13     class A{
14  
15         private A a = null;
16         
17         public A getA(){
18             if(a == null)
19                 a = new A();
20             return a;
21         }
22     }
23 }

饿汉式:

 1 public class test1 {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         test1.A aa = new test1().new A();
 9         test1.A b = aa.getA();
10         System.out.println("ok");
11     }
12 
13     class A{
14  
15         private A a = new A();
16         
17         public A getA(){
18             return a;
19         }
20     }
21 }

懒汉式容易线成不安全,饿汉式加载占内存

猜你喜欢

转载自www.cnblogs.com/feichangnice/p/9117962.html