DatabaseConnectionHandler

DatabaseConnectionHandler

我正在使用一个类和一些子类的项目中。声明Database类时,出现以下错误:

Exception in thread "main" java.lang.StackOverflowError
    at data.DatabaseConnectionHandler.<init>(DatabaseConnectionHandler.java:12)
    at data.Database.<init>(Database.java:18)


最后两行重复大约10000次。

Database是我的父类,而DatabaseConnectionHandler是子类。在Database类中,我声明了DatabaseConnectionHandler的实例,我认为这可能是原因,但我不知道为什么。

Database类别:

public class Database {

    protected static Connection connection = null;
    protected static Statement statement = null;
    protected static ResultSet resultSet = null;

    DatabaseConnectionHandler DBCH = new DatabaseConnectionHandler(); //Line 18
    Registration regis = new Registration();

    public Database() throws SQLException {

        DBCH.openConnection();

    }


DatabaseConnectionHandler类:

public class DatabaseConnectionHandler extends Database {

    private final String URL = "jdbc:mysql://localhost:3306/foo_bar";
    private final String USERNAME = "foo";
    private final String PASSWORD = "bar";

    public DatabaseConnectionHandler() throws SQLException {} //line 12

    protected void openConnection() {

    try {

        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        connectionStatus = true;

    } catch (SQLException | ClassNotFoundException exe) {

        System.out.println(exe);

        connectionStatus = false;

    }

}


Database()声明DatabaseConnectionHandler()导致此错误?如果是这样,我该如何解决?如果不是,那是什么引起了问题,又该如何解决?

最佳答案

创建Database时,还创建一个DatabaseConnectionHandler

public class Database {

    //...
    DatabaseConnectionHandler DBCH = new DatabaseConnectionHandler();
    //...

}


DatabaseConnectionHandlerDatabase

public class DatabaseConnectionHandler extends Database {

    //...

}


因此,创建Database要求创建一个Database。这是无限递归。

您有两种选择:


创建DatabaseConnectionHandler时不要创建Database
本身没有DatabaseConnectionHandler就是Database

09-25 22:24