<<< Using static methods and constant data | Index | static Initialization Block, cont. >>> |
static fields and static methods differ from instance variables and regular methods.
Java allows a special code block to initialize the static fields:
public class className { // any field declarations private static DBConnection connection; static { // any initialization statements for static fields try { String url = "jdbc:mysql://localhost:3306/SampleDB"; String user = "robert"; String password = "secret"; connection = DBDriverManager.getConnection( url, user, password ); } catch (Exception ex) { System.err.println( "Error: unable to connect to the database." ); } } // the rest of the class }
<<< Using static methods and constant data | Index | static Initialization Block, cont. >>> |