简体   繁体   中英

StackOverflowError caused by class declaring subclass?

I am working on a project that uses a class and some subclasses. When I declare my Database class, I get this error:

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

These last two lines repeat themselves for about another 10000 times.

Database is my parent class and DatabaseConnectionHandler is the subclass. In the Database class, I declare a instance of DatabaseConnectionHandler , I think this might be the cause, but I don't know why.

Database Class:

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();

    }

And DatabaseConnectionHandler Class:

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;

    }

}

Is Database() declaring DatabaseConnectionHandler() causing this error? If so, how do I fix this and if not, what is causing the problem then and how do I fix that?

When you create a Database , you also create a DatabaseConnectionHandler :

public class Database {

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

}

And a DatabaseConnectionHandler is a Database :

public class DatabaseConnectionHandler extends Database {

    //...

}

So creating a Database requires creating a Database . This is an infinite recursion.

You have two options:

  1. Don't create a DatabaseConnectionHandler when creating a Database
  2. Don't have a DatabaseConnectionHandler itself be a Database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM