黑马程序员技术交流社区

标题: static块中调用非static的构造函数为什么不报错? [打印本页]

作者: 哈皮哈皮doge    时间: 2015-8-24 13:12
标题: static块中调用非static的构造函数为什么不报错?
public class TestSingle {
        private static TestSingle s = null;
        private TestSingle(){}
        public static TestSingle getInstance(){
                if(s == null){
                        synchronized(TestSingle.class){
                                if (s == null)
                                        s = new TestSingle();
                        }
                }
                return s;
        }   
}
在静态的getInstance方法中使用s = new TestSingle(),而TestSingle()的构造函数不是非静态的吗,这样为什么不报错?
作者: Cancer    时间: 2015-8-24 14:44
public static TestSingle getInstance(){,你确定你的构造函数是这么定义的
作者: 哈皮哈皮doge    时间: 2015-8-24 14:50
Cancer 发表于 2015-8-24 14:44
public static TestSingle getInstance(){,你确定你的构造函数是这么定义的

getInstance方法不是构造函数啊
作者: Cancer    时间: 2015-8-24 14:59
构造方法要与类名相同;例如这样:
  1.         public class test1 {
  2.                
  3.                 int age;
  4.                 public test1(){//无参构造方法
  5.                        
  6.                 }
  7.                 public test1(int age){//带参构造方法
  8.                         this.age=age;
  9.                 }
复制代码

构造方法没有返回值类型
作者: 哈皮哈皮doge    时间: 2015-8-24 15:09
Cancer 发表于 2015-8-24 14:59
构造方法要与类名相同;例如这样:
构造方法没有返回值类型

有啊,private TestSingle(){}不就是吗,你还没明白我的意思,我是说在getInstance()方法中通过new TestSingle(),getInstance()方法是static的,但是TestSingle()这个构造函数并不是static的,这样是为什么?
作者: Cancer    时间: 2015-8-24 15:58
我试着照你的代码写了,一边没有报错啊,是不是的编辑器有问题啊
作者: 哈皮哈皮doge    时间: 2015-8-24 20:02
Cancer 发表于 2015-8-24 15:58
我试着照你的代码写了,一边没有报错啊,是不是的编辑器有问题啊

额,我就是想知道为什么不报错,理论上应该报错的啊




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2