Fix cannot make static reference to non-static method

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 exist. Since we did not create an object of JavaHelloWorld, nonstatic method sayHello() does not exist yet


Now you can solve this in two ways.

Declare sayHello method static

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

Output:

Hello world

Call sayHello() from JavaHelloWorld object

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

Output:

Hello world

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

Was this post helpful?

Leave a Reply

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