Fix cannot make static reference to non-static method

Previous
Next

In this post, we will see how to solve cannot make static reference to non-static method.

Let’s understand this error with the help of example.

Above program won’t compile and you will get below compilation error.
JavaHelloWorld
It says “cannot make static reference to non-static method sayHello from the type JavaHelloWorld”


Why are you getting this error?

The answer is very simple. You can not call something that does not exists.Since we did not create object of JavaHelloWorld, non static method sayHello() does not exists yet


Now you can solve this by two ways.

Declare sayHello method static

You can declare sayHello() method static and compiler won’t complain any more.


Call sayHello from JavaHelloWorld object

You can create an object of JavaHelloWorld class and call sayHello world from it.

That’s all about how to fix cannot make static reference to non-static method in java

Previous
Next

Add Comment