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.
[toc]
Let’s understand this error with the help of example.

package org.arpit.java2blog;

public class JavaHelloWorld {

    public static void main(String args[])
    {
        sayHello();
    }

    public void sayHello()
    {
        System.out.println("Hello world from java2blog");
    }
}

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.

package org.arpit.java2blog;

public class JavaHelloWorld {

    public static void main(String args[])
    {
        sayHello();
    }

    public static void sayHello()
    {
        System.out.println("Hello world");
    }
}

Output:

Hello world

Call sayHello() from JavaHelloWorld object

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

package org.arpit.java2blog;

public class JavaHelloWorld {

    public static void main(String args[])
    {
        JavaHelloWorld jhw=new JavaHelloWorld();
        jhw.sayHello();
    }

    public void sayHello()
    {
        System.out.println("Hello world");
    }
}

Output:

Hello world

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.