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
).
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.
The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.
A static method can call only other static methods; it cannot call a non-static method.
You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program.
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:
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With