"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why am I getting the \"Cannot Make a Static Reference to a Non-Static Field\" Error in Java?

Why am I getting the \"Cannot Make a Static Reference to a Non-Static Field\" Error in Java?

Published on 2024-11-07
Browse:370

Why am I getting the \

Avoiding the "Cannot Make a Static Reference to a Non-Static Field" Error

In Java programming, the "cannot make a static reference to a non-static field" error occurs when trying to access a non-static field (also known as an instance variable) within a static method.

In the provided code, the error arises because the main method is declared as static, meaning it can only refer to static members of the class, including static methods and fields. However, the fields balance and annualInterestRate are non-static, which means they are unique to each instance of the Account class.

To resolve this error, it is necessary to modify the code to follow appropriate Java syntax:

  • > Remove Static References to Non-Static Fields:

    • The references to balance and annualInterestRate within the main method should be removed because they are instance variables accessed through an object reference (e.g., account.getBalance(), account.getAnnualInterestRate())
  • > Make Non-Static Methods Instance Methods:

    • The withdraw and deposit methods should be declared as non-static, as they need to access the balance field through an object reference. This allows them to modify the balance of specific Account instances.

Revised Code for main Method:

public static void main(String[] args) {
    Account account = new Account(1122, 20000, 4.5);

    account.withdraw(2500);
    account.deposit(3000);
    System.out.println("Balance is "   account.getBalance());
    System.out.println("Monthly interest is "   account.getAnnualInterestRate() / 12);
    System.out.println("The account was created "   account.getDateCreated());
}

Revised Code for withdraw and deposit Methods:

public void withdraw(double withdrawAmount) {
    balance -= withdrawAmount;
}

public void deposit(double depositAmount) {
    balance  = depositAmount;
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3