confusion...

Hi,

In the following code, they define a class called StatementTest and inside it , they define again an instance of it . What they are doing ? I am confused with it.

import java.sql.Connection;

import java.sql.Statement;

import java.sql.PreparedStatement;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

public class StatementTest {

public static void main(String[] args) {

try {

StatementTest SQLExample = new StatementTest();

SQLExample.doStatement();

SQLExample.doPreparedStatement();

} catch(SQLException sqle) {

System.err.println(揝QL Exception: ?+ sqle);

} catch(ClassNotFoundException cnfe) {

System.err.println(cnfe.toString());

}

}

Connection databaseConnection; //

String driverName; //

String sourceURL; //

}

[946 byte] By [Sangfroida] at [2007-11-26 17:12:52]
# 1

Because main is a static method they create an instance of that class then call mehtods via the instance rather than the class it's self. You can not call a non static method from a static method (without using it's full name).

Try it yourself. Do you use and IDE? Eclipse maybe. create a class with a main and then put a method in there which is not static and try to call it. You will get an error.

kikemellya at 2007-7-8 23:40:45 > top of Java-index,Java Essentials,New To Java...
# 2
well i got confused why they are creating instance of the class itself inside the same class.public class ""StatementTest"" {public static void main(String[] args) {try {"StatementTest SQLExample = new StatementTest();"
Sangfroida at 2007-7-8 23:40:45 > top of Java-index,Java Essentials,New To Java...
# 3

You need to read up on static and non-static.

A class is a blueprint of your code, in most cases you create a copy (instance) of that code and then use this rather than the class directly. Imagine you have a seperate class called "AppStart" and this had the main method you have in your current class, you would create the instance of the current class you have and then class that classes methods from your instance which is in your "AppStart" class. Well this is no different.

http://www.leepoint.net/notes-java/flow/methods/50static-methods.html

http://mindprod.com/jgloss/static.html

http://www.geom.uiuc.edu/~daeron/docs/javaguide/java/anatomy/static.html

kikemellya at 2007-7-8 23:40:45 > top of Java-index,Java Essentials,New To Java...
# 4
Thanks a lot...I will first go through your links :)...If I have any confusion, I will write up..
Sangfroida at 2007-7-8 23:40:45 > top of Java-index,Java Essentials,New To Java...
# 5
I had seen only programs which had main method and instantiated other classes...but this one is instantiating itself...that is what made me confused...
Sangfroida at 2007-7-8 23:40:45 > top of Java-index,Java Essentials,New To Java...