接口:TestDao 实现类:TestDaoimpl
现有如下3个问题:
1,private TestDao testdao 与private TestDao testdao = new TestDaoimpl()有什么区别?
2,我用前者调用实现类的方法的时候出现空指针异常,但又看到其他例子也用前者调用却没出现这种错误,这是为什么呢?
3, private TestService testService;
[color=red]public TestService getTestService() {
return testService;
}
public void setTestService(TestService testService) {
this.testService = testService;
}[/color]
不写红色部门会报错,这是为什么呢?红色部分有什么意义和用处?
小弟彻夜难眠?希望各位兄弟帮忙,谢谢!!
1.private TestDao testdao
2.private TestDao testdao = new TestDaoimpl()
第一个没有初始化,java实例化对象的时候对象的初始值是null,实际上第1句相当于
private TestDao testdao = null;
所以会出现空指针异常
3,private TestService testService;
public TestService getTestService() {
return testService;
}
public void setTestService(TestService testService) {
this.testService = testService;
}
3处是标准java Bean的写法,第三方框架实例化对象的时候会通过set方法为对象赋值,也就是传说中的反射。
private TestDao testdao 与private TestDao testdao = new TestDaoimpl()有什么区别? 是有去别的,前者只定义,没有初始化。
你应该有用Spring吧,这个是依赖注入的原理,
public void setTestService(TestService testService) {
this.testService = testService;
}
如果没写这句的话,他就不能将生成好的值注入进来,所以你调用getTestService()会出现空异常。