44 Views

23rd June 2020

Why A Non-static Variable Cannot Be Referenced From A Static Context?

While I’m working on a Java program, I got this compiler error: non-static variable count can not be referenced from a static context. Can anyone tell me What does it mean, why this error occurs, and How to fix this error?

Answers

23rd June 2020

Answered by Dikshit Jain

Hey Kusum,
 

The non-static variable cannot be referenced from a static context is compiler error that occurs when the user tries to put program code to access a non-static variable inside main in Java that is static.

public class Static Test{
	Private int count=0;
	public static void main(String args[]) throws IOException{
		count++; //compiler error: non-static variable count cannot be referenced from a static context
	}
}

 

6th November 2020

Answered by paul wings

Java main() method cannot access a non-static member of its class. That means, public static void main(String[] args) is a static method. Instance variables (variables defined in the class but not marked as static keyword) cannot be accessed from a static method without referencing an instance of the class. An attempt to use the variables and methods of the class which do not have the static modifier without creating an instance of the class is caught by the Java compiler at compile time and flagged as an error: Cannot Be Referenced From a Static Context

Solutions:

  • Either make that variable static.
  • Make the calling function non-static.
  • Inside the calling function, create an object first and then access the non-static variable.

Static methods are useful if you have only one instance where you're going to use the method, and you don't need multiple copies (objects). Non-static methods are used if you're going to use your method to create multiple copies. 

 

Write your answer

STILL GOT QUERIES?

Get a Live FREE Demo
  • Explore the trending and niche courses and learning maps
  • Learn about tuition fee, payment plans, and scholarships
  • Get access to webinars and self-paced learning videos