I have an abstract class that has heirs. In the heirs I read data from external files in class constructors - the operation is the same for all heirs. I decided to implement reading in the class of the parent. As a result, I get the error "NullPointerException" This is how it is implemented in the parent class.

public abstract class Parent { private ArrayList<Campaign> listOfCampaigns; private ArrayList<Campaign> filteredCampaigns; private String[] campaignsPath; Parent(){ super(); listOfCampaigns = readListOfCampaigns(campaignsPath); // считывание } public double find(Request request){ // Первичная фильтрация filteredCampaigns = filterCampaigns(listOfCampaigns, request); return 1; } protected ArrayList<Campaign> filterCampaigns (ArrayList<Campaign> totalListOfCampaigns, Request request){ for ( int i = 0; i < totalListOfCampaigns.size(); i++ ){ // Вот и вылезает ошибка NullPointerException ... ... } } } 

Why the error gets out?

  • well then in totalListOfCampaigns you have nothing to transmit - Gorets
  • @Gorets: why nothing? surely null :) - VladD
  • Why so? I read the data in the listOfCampaigns, and then call the filterCampaigns method in the find method, passing it the parameters listOfCampaigns, request - Stas0n
  • Try writing at the beginning of the filterCampaigns method if (totalListOfCampaigns == null) throw new Exception (); (temporarily, for debugging). If you really do not pass null , it does not hurt. - VladD
  • Yes, there is an error even earlier - writes that campaignsPath is empty - Stas0n

2 answers 2

super() calls the parent class constructor, and you call a method for a class that has no parent. Describe the parent class constructor, then refer to it in the inherited class inside the constructor of this class. Those someClass(){super()}

  • Usually jvm when compiling itself creates an empty constructor, if it is not written - Gorets
  • By the way, what does having a parent mean? And the Object? - rasmisha
  • @rasmisha here means the class that does not implement any other class - Stas0n
  • Well, rather, "extendend") And secondly, just from Object all classes without an explicitly specified parent are implicitly inherited. - rasmisha
  • oh, blame, earned - of course an expendit) - Stas0n

Yes, here it is empty. But further, in the heirs I also have the field campaignsPath. And they are not empty there.

@ Stas0n , i.e. you for some reason override the campaignsPath field in the heir? Then, of course, the parent class will never know, then you put it there. He can only look into his fields.

I suggested not to override, but to pass to the parent's constructor.

Well, or make the field campaignsPath not private , but protected . Although the option with the designer is more beautiful.

  • Already fixed. Passing the campaignsPath constructor. Thank! - Stas0n