How to inherit from the main class in java
I have two java classes. One is NewFrame.java where the forms(buttons, textfields) are located. And the other one is Main.java where I have put the connection string for mysql:
Main.java looks like this:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_record", "root", "password");
PreparedStatement statement = con.prepareStatement("select * from employee");
开发者_JS百科 ResultSet result = statement.executeQuery();
}
}
How do I inherit from the main.java so that the declarations in it would be universally accessible to the forms in NewFrame.java? Please help. Thanks
A better way to solve it is to create a utility class
public class DataBaseHandler{
public static Connection getConnection(){
//...
}
public static Object executeQuery(String query){
//...
}
}
Assuming NewFrame extends JFrame or Frame you cannot do it via inheritance as Java only supports single implementation inheritance (extends) and multiple interface inheritance (implements).
You would probably do it something like:
public abstract class DatabaseFrame
extends JFrame
{
// common code goes here
}
public class NewFrame
extends DatabaseFrame
{
// will have to have a main method here
}
And then pull the code that is currently in main out and put into method(s)/variable(s) in the abstract class.
You would need to expose the connection to external classes, if you hust need to execute statements on it just provide Main.java
with
public static ResultSet executeStatement(String string) throws SQLException
{
return con.prepareStatement(string).executeQuery();
}
Note that you must either catch or throw back the SQLException
.. and the connection needs to be static. This will allow you to execute a query by invoking Main.executeStatement("select ...");
This approach is simple but could be more object-oriented, maybe in your case is ok anyway since you seem to need just one connection.
A static import will get you most of the way there. That being said I can't discourage its use enough, it really goes against the spirit of object oriented programming.
精彩评论