Home > Java > javaTutorial > Why Can't I Access a Non-Static Variable from a Static Method in Java?

Why Can't I Access a Non-Static Variable from a Static Method in Java?

Barbara Streisand
Release: 2024-12-30 18:54:09
Original
836 people have browsed it

Why Can't I Access a Non-Static Variable from a Static Method in Java?

Error: Non-static Variable Cannot Be Referenced from a Static Context

In your code, you declare a class variable count and attempt to access it within a static method main. This error occurs because variables declared within a non-static context cannot be directly referenced from a static context.

Understanding Static and Non-Static Contexts:

  • Static Context: Refers to a class itself, independent of any specific instance. Static methods and variables belong to the class, not to individual instances.
  • Non-Static Context: Refers to a specific instance of a class. Non-static methods and variables belong to an object and vary based on the instance.

In your example, count is a non-static variable, meaning it is specific to each instance of the MyProgram class. To fix the error, you need to create an instance of MyProgram and access count within its non-static method.

Solution:

  1. Create an instance of the MyProgram class:
MyProgram obj = new MyProgram();
Copy after login
  1. Access count within a non-static method:
public void run() {
    System.out.println(count);
}
Copy after login
  1. Call the run method from the main method:
public static void main(String[] args) {
    MyProgram obj = new MyProgram();
    obj.run();
}
Copy after login

By following these steps, you ensure that the non-static variable count is accessed within a non-static context.

The above is the detailed content of Why Can't I Access a Non-Static Variable from a Static Method in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template