Java: How to Call Non Static Method from Main Method

Java: How To Call Non Static Method From Main Method?

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.

How do I call a non static method from a main method?

You can't. A non-static method is one that must be called on an instance of your Test class; create an instance of Test to play with in your main method:

public class Test {

public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };

Test test = new Test();
test.arrPrint(arr);

}

public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);

}
}

Java conventions for calling non-static methods from the main() method

That's exactly how.

Create an object instance. Call the methods on the instance.

For example, this is a typical code in a Springboot application.

An instance of SpringApplication is created and then the instance method run is invoked.

public class Application {

public static void main(final String[] args) {

final SpringApplication application =
new SpringApplication(Application.class);
application.run(args);
}
}

As for the name of the "main" method, in the example above run makes sense because you want to run the application.

But it could be anything like run, execute, start, serve, scan it depends on what your program does.

In your specific case I would call it calculateFibonacci, or if your class was named Fibonnacci then just calculate()



Is this how you would do it or what should I change?

I think your code looks good.

The way I would've written would be as follows

public class Fibonacci {

public static void main(String[] args) {
Fibonacci fibonacci = new Fibonacci();
fibonacci.execute();
}

public void execute(){
System.out.println(fibonacci(10));
}

public int fibonacci(int n){

if (n <= 0){
throw new IllegalArgumentException(
"n must be greater then 0. Received: " + n);
}

if (n == 1 || n == 2){
return 1;
}

return fibonacci(n - 2) + fibonacci(n - 1);
}
}

The reason for the exception instead of null it to indicate that's an actual invalid (or illegal) argument. The program can't calculate, whereas null would indicate the computation for a negative number results in null which is not the case.

But the way you have it is completely fine.

How to call a non-static method from main in Java?

There is a lot going on here that needs to be rectified fast--especially with finals coming soon.

First, you need to understand how your Sphere class is supposed to work. Every instance of Sphere is its own thing and knows how to do things. All a Sphere needs to be given is its diameter (or radius), and with that, it can figure out everything it needs to about itself. It can calculate its volume and surface area, and it can print itself out in toString.

So you want Sphere to look like this:

public class Sphere {
public double diameter;

public Sphere(double diameter) {
this.diameter = diameter;
}

public double volume() {
return (4.0 / 3.0) * (Math.PI) * Math.pow((diameter / 2.0), 3);
}

public double surfaceArea() {
return (4) * (Math.PI) * (Math.pow((diameter / 2.0), 2));
}

public String toString()
{
return "The diameter of this sphere is " + diameter + ", the volume is " + volume() + ", and the surface area is " + surfaceArea() + ". ";
}
}

Notice how Sphere has a constructor, which is how we create new instances of Sphere. We do so with just the diameter. Once it has that, the instance of Sphere can do everything Spheres do.

Notice also there is no static. I have no idea why you are so in love with static.

You should know that static anything means that every instance of the class shares it. That won't apply to Spheres because each instance has its own diameter. It isn't like a bunch of Spheres share a diameter. Some might have equal diameters, but they still are their own. It's like how you and I could drive Bentleys (wishful thinking) that are identical in every way, but they are still two different cars. Of course static things can't access non-static things because non-static things need to be part of an object instance that may not be available.

Finally, in your main class Assignment6, you simply do something like this:

Sphere s = new Sphere(5);

to create a an instance of Sphere with diameter 5. Now s can tell us its volume, surface area, and its description via toString.

I'm not actually sure what your assignment is, but hopefully this will help you out.

How do I access a non static method from main method in the same class?

You can make the method static or you create a new instance of the class and access to it like that:

Test test = new Test();
test.yourMethod();

Accessing non-static members through the main method in Java

The main method does not have access to non-static members either.

public class Snippet
{
private String instanceVariable;
private static String staticVariable;

public String instanceMethod()
{
return "instance";
}

public static String staticMethod()
{
return "static";
}

public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Snippet.staticMethod()); // ok

System.out.println(new Snippet().instanceMethod()); // ok
System.out.println(new Snippet().instanceVariable); // ok

System.out.println(Snippet.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}

Calling Non-Static Method In Static Method In Java

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

Can't call non static method

Create an instance of your class

public static void main(String[] args){

String filename = null;
System.out.println("Type the filename you wish to act upon.");
Scanner scanIn = new Scanner(System.in);
filename = scanIn.next();
Sound sound = new Sound();
sound.wavRead(fileName);
}

It's an instance method, it requires an instance to access it. Please go through the official tutorials on classes and objects.



Related Topics



Leave a reply



Submit