码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-31 19:27:25      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:不能   自身   col   static   color   ret   空白   todo   实例   

答案是不能。

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

 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 }

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

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

标签:不能   自身   col   static   color   ret   空白   todo   实例   

原文地址:https://www.cnblogs.com/feichangnice/p/9117962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!