In this post, we will see how to solve cannot make static reference to non-static method.
Table of Contents
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; public class JavaHelloWorld { public static void main(String args[]) { sayHello(); } public static void sayHello() { System.out.println("Hello world"); } } |
Output:
Call sayHello() from JavaHelloWorld object
You can create an object of JavaHelloWorld
class and call sayHello()
from it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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:
That’s all about how to fix cannot make static reference to non-static method in java