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:
> Make Non-Static Methods Instance Methods:
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;
}
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