如何从java中的主类继承

如何从java中的主类继承,java,mysql,Java,Mysql,我有两个java类。一个是NewFrame.java,其中包含formsbuttons和textfields。另一个是Main.java,我把mysql的连接字符串放在这里: Main.java如下所示: public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception {

我有两个java类。一个是NewFrame.java,其中包含formsbuttons和textfields。另一个是Main.java,我把mysql的连接字符串放在这里:

Main.java如下所示:

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");
        ResultSet result = statement.executeQuery();

    }
}

如何从main.java继承,以便NewFrame.java中的表单可以普遍访问其中的声明?
请帮忙。谢谢

假设NewFrame扩展了JFrame或Frame,您不能通过继承来实现,因为Java只支持单实现继承扩展和多接口继承实现

您可能会这样做:

public abstract class DatabaseFrame 
    extends JFrame
{
   // common code goes here
}

public class NewFrame
    extends DatabaseFrame
{
   // will have to have a main method here
}

然后将当前在main中的代码提取出来并放入抽象类中的方法/变量。

假设NewFrame扩展了JFrame或Frame,您不能通过继承来实现,因为Java只支持单实现继承扩展和多接口继承实现

您可能会这样做:

public abstract class DatabaseFrame 
    extends JFrame
{
   // common code goes here
}

public class NewFrame
    extends DatabaseFrame
{
   // will have to have a main method here
}

然后将当前在main中的代码取出并放入抽象类中的方法/变量。

您需要公开与外部类的连接,如果您不需要在其上执行语句,只需为main.java提供

请注意,您必须捕获或抛出SQLException。。连接需要是静态的。这将允许您通过调用Main.executeStatementselect


这种方法很简单,但可能更面向对象,因为您似乎只需要一个连接,所以在您的情况下也可以。

您需要将连接公开给外部类,如果您不需要在其上执行语句,只需为Main.java提供

请注意,您必须捕获或抛出SQLException。。连接需要是静态的。这将允许您通过调用Main.executeStatementselect


这种方法很简单,但可能更面向对象,因为您似乎只需要一个连接,所以在您的情况下,可能还是可以的。尽管如此,我还是不能充分地阻止它的使用,它确实违背了面向对象编程的精神。

A将为您提供大部分方法。尽管如此,我还是不能阻止它的使用,它确实违背了面向对象编程的精神。

更好的解决方法是创建一个实用程序类

public class DataBaseHandler{
  public static Connection getConnection(){
     //...
  }

  public static Object executeQuery(String query){
     //...
  }
}

更好的解决方法是创建一个实用程序类

public class DataBaseHandler{
  public static Connection getConnection(){
     //...
  }

  public static Object executeQuery(String query){
     //...
  }
}