由类声明子类引起的StackOverflowError?

时间:2016-11-11 15:10:16

标签: java class stack-overflow subclass

我正在开发一个使用类和一些子类的项目。当我声明我的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()导致此错误?如果是这样,我该如何修复此问题,如果没有,那么是什么导致了问题,我该如何解决?

1 个答案:

答案 0 :(得分:4)

创建Database时,您还可以创建DatabaseConnectionHandler

public class Database {

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

}

DatabaseConnectionHandlerDatabase

public class DatabaseConnectionHandler extends Database {

    //...

}

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

您有两种选择:

  1. 创建DatabaseConnectionHandler
  2. 时,请勿创建Database
  3. 不要DatabaseConnectionHandler本身为Database