How to call non static method from static method in Java

Hello learners, today we will learn how to call a non-static method from a static method in Java with the help of this small tutorial. Method calling in java is easy but when you try to call a non-static method inside a static method you will get an error message like this:

Error Message :

error: non-static method name_of_method() cannot be referenced from a static context.

Now how to fix this error?

The way to remove this error is to call the non-static method using an instance of the class where it resides, for which we need to create an object of that class.

Calling Non-Static method from Static method in Java

Now without wasting time let’s hit the code section for a better understanding of the concept. Observe this code given below and try to predict the output.

public class Main {

static public void one() {
System.out.println("static method");
//two(); --> this will give you an error bcoz method two is non-static method
Main m = new Main();
m.two();
}

public void two() {
System.out.println("Non-static method");
}

public static void main(String[] args) {
System.out.println("static main method");
one();
}
}

OUTPUT:

static main method                                                                                                                                             
static method                                                                                                                                                  
Non-static method

Inside the main method, method one is called (on line 14) and it works fine because method one is declared as static and easily called by another static method.

But on-line 6 if you try to do the same, you can not do that because method two is an instance method. To call an instance method within a static method you need to create an object of the class where the method resides.

You can try it on your own, just copy and paste the code in the editor and run it by removing the ‘//’ at line 6 and it will give you the compile-time error.

So, after creating the object of the main class now you can call the method two on this object.

You can learn about java high order functions for advance knowledge.

So, that’s all for now about method calling in java, till then Keep Learning, Keep Practicing, Keep Reading!

“THINK TWICE CODE ONCE!”

Leave a Reply

Your email address will not be published. Required fields are marked *