How to Fix Error “Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context”

Error: Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context

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:

Leave a Reply

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