Java: How To Call Non Static Method From Main Method?
Java is a kind of object-oriented programming, not a procedure programming. So every thing in your code should be manipulating an object.
public static void main is only the entry of your program. It does not involve any object behind.
So what is coding with an object? It is simple, you need to create a particular object/instance, call their methods to change their states, or do other specific function within that object.
e.g. just like
private ReportHandler rh = new ReportHandler();
rh.<function declare in your Report Handler class>
So when you declare a static method, it doesn't associate with your object/instance of your object. And it is also violate with your O-O programming.
static method is usually be called when that function is not related to any object behind.
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.
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}