Home >Java >javaTutorial >Why Can\'t I Access a Non-Static Field from a Static Method in Java?
Non-Static Field Reference in Static Context
In Java, static methods cannot access non-static fields directly. This error typically occurs when attempting to access an instance variable from a static method.
Understanding the Problem
In the given code, the error occurs in the main method:
<code class="java">Account account = new Account(1122, 20000, 4.5); account.withdraw(balance, 2500);</code>
Here, the withdraw() method is static, but it tries to access the non-static field balance. Since the main method is static, it cannot refer to instance variables like balance.
Solution
To resolve this error, make either the method non-static or the field static.
Option 1: Make the Withdraw Method Non-Static
Change the withdraw() method to:
<code class="java">public void withdraw(double withdrawAmount) { balance -= withdrawAmount; }</code>
Now, the method can access the balance field since it's non-static.
Option 2: Make the Balance Field Static
Alternatively, make the balance field static:
<code class="java">private static double balance = 0;</code>
Now, the balance field can be accessed from static contexts like the main method:
<code class="java">Account account = new Account(1122, 20000, 4.5); account.withdraw(balance, 2500);</code>
The above is the detailed content of Why Can\'t I Access a Non-Static Field from a Static Method in Java?. For more information, please follow other related articles on the PHP Chinese website!