stighy stighy - 4 months ago 8
Java Question

Java: how to call non static method from main method?

I'm learning java and now i've the following problem: I have the main method declared as

public static void main(String[] args) {

..... }


Inside my main method, because it is static I can call ONLY other static method!!! Why ?

For example: I have another class

public class ReportHandler {
private Connection conn;
private PreparedStatement prep;
public void ExecuteBatchInsert() { ....
} }


So in my main class I declare a
private ReportHandler rh = new ReportHandler();


But I can't call any method if they aren't static.

Where does this go wrong?

EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the
static void main
).

Answer

You simply need to create an instance of ReportHandler:

ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions

The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.

It's really important that you understand that:

  • Instance methods (and fields etc) relate to a particular instance
  • Static methods and fields relate to the type itself, not a particular instance

Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).

Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.