aspose file tools*
The moose likes Beginning Java and the fly likes Accessing implemented class methods through interface reference without constructor i Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing implemented class methods through interface reference without constructor i" Watch "Accessing implemented class methods through interface reference without constructor i" New topic
Author

Accessing implemented class methods through interface reference without constructor i

satyam kaushik
Greenhorn

Joined: Jun 09, 2012
Posts: 3
I have a class CommonDaoImpl that implements an interface CommonDao.Now i am trying to access the getRegisterData() of CommonDaoImpl through interace CommonDao reference like this

public class CommonServiceImpl implements CommonService { CommonDao commonDao public boolean insertRegisterData(CommonBean objCommonBean) {

return commonDao.getRegisterData(objCommonBean);
}
but it is not working and thow an NullPointerException

So i slightly change my code and initialize interface reference with the constructor of implemented class CommonDao impl like this

public class CommonServiceImpl implements CommonService { CommonDao commonDao=new CommonDaoImpl();

public boolean getRegisterData(CommonBean objCommonBean) {


return commonDao.insertRegisterData(objCommonBean);
}
But i could not understand why it happens...Please help me out..Thanks in advance.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14352
    
  22

Welcome to the Ranch. The code you posted is a little bit hard to read. Please use code tags, so that the forum software can properly format your code.

Member variables are initialized to null by default (if you don't initialize them explicitly). In your first example, the member variable commonDao will be null, because you don't initialize it. If you try to call a method on a variable that's null, you'll get a NullPointerException. It must be initialized to refer to some object before you try to call any methods on it.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing implemented class methods through interface reference without constructor i