You may encounter “Error: Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context” when starting to learn about non-access modifiers, in this case the static
keyword. Continue reading to learn how to fix the error.
The cause of the error “Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context“
Example of error:
import java.util.*;
class MyClass {
public String name = "learnshareit.com";
public MyClass() {}
public void sayName() {
System.out.println(name);
}
public static void main(String[] args) {
MyClass.sayName();
}
}
Output:
MyClass.java:10: error: non-static method sayName() cannot be referenced from a static context
MyClass.sayName();
Understanding the problem
The static
keyword: Is a non-access modifier for the Methods and Properties/Attributes/Variables of a Class, which lets you access them without the need to create an instance of that Class.
⇒ The error is thrown when a non-static variable/method is accessed without the creation of an instance of the Class containing it.
How to fix this error?
Solution 1: Making the variable static
The most direct way to solve the issue. Simply add the static
keyword to the variable. Here is the example to fix it:
import java.util.*;
class MyClass {
public static String name = "learnshareit.com";
public MyClass() {}
public static void sayName() {
System.out.println(name);
}
public static void main(String[] args) {
MyClass.sayName();
}
}
Output:
learnshareit.com
Solution 2: Creating an instance of the Class
In the case that you need the variable to be non-static, you would need to create an instance of the Class containing the variable. You can try this way:
import java.util.*;
class MyClass {
public String name = "learnshareit.com";
public MyClass() {}
public void sayName() {
System.out.println(name);
}
public static void main(String[] args) {
MyClass _class = new MyClass();
_class.sayName();
}
}
Output:
learnshareit.com
Summary
You can fix the error "
Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context"
either by making the variable in question static or creating an instance of the Class containing the variable
Maybe you are interested:
- Could not reserve enough space for 2097152kb object heap
- ERROR : ‘compileJava’ task (current target is 11) and ‘compileKotlin’ task (current target is 1.8) jvm target compatibility should be set to the same Java version in Java
- java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.
Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP