samedi 30 juin 2018

Java NullPointerException occurred at the same of the construction

Sorry if this question has been answered already. I am written a java program, where I am trying to use the factory pattern to encapsulate SQL statement queries. For this, I create a SQL interface which I use to declare a variable on another abstract class (no instantiation). Instantiation of SQL query variable is done in the constructor of the concrete class. For example :

public abstract class ProductList {
    private  Connection connection;
    private DataBaseDAO dbInstance; //DataBaseDAO uses singleton
    protected  ResultSet results;
    private  Statement statement;
    protected  SqlQuery sqlquerry; //abstract product


    public ProductList(){
        dbInstance = DataBaseDAO.getInstance();
        if(dbInstance.open()) {
            try{
                connection = dbInstance.getConnection();
                statement = connection.createStatement();
                statement.execute(sqlquerry.createTable()); //To be defined

            }catch(Throwable t) {
                t.printStackTrace();
            } finally {
                try{
                    statement.close();
                } catch (SQLException e)  {
                    e.printStackTrace();
                }
            }
        }
    }
}

Implementing the ProductList concrete class, with a concrete instance of SQL query

public class GenericProductList extends ProductList {
    public GenericProductList() {
       this.sqlquery = new StandardProductSqlQuery(); //instantiating 
    }
}

I create an instance of the GenericProductList, as for example:

public class Main {
    public static void  main(String[] args){
        ProductList generic = new GenericProductList();
    }
}

The problem is whenever I run the program I get the following java.lang.NullPointerException which can be traced to the following line:

 statement.execute(sqlquerry.createTable());

 public GenericProductList() 

 ProductList generic = new GenericProductList();

NullPointerException screenshot

What did I do wrong? Thanks for looking and answering!

Aucun commentaire:

Enregistrer un commentaire